skip to Main Content

I’m having a weird issue when trying to center an element that has aspect-ratio applied. I’d assume it would behave similarly to how centering an image works but I keep ending up with an element of 0px x 0px.

https://codepen.io/richardcool/pen/xxeKOwp

I have created a basic CodePen to show the issue. If I uncomment the align-items: center line then the element becomes 0px x 0px. I have also tried centering using absolute positions and get the same issue.

Any thoughts?

2

Answers


  1. For aspect ratio to work properly with alignment like flex, you need to specify an actual width or height on the element, otherwise there is no base value for CSS to calculate with, even if you specify max-width.

    Set the poster div to a width of 100%. Your max-width will override it, but then you’ll be able to vertically center it with align-items: center on the parent.

    Login or Signup to reply.
  2. As long as there is no content in your div that determines the size, you have to specify either a width or a height when using aspect-ratio and align-items: center. For example like this:

    <div class="video">
      <div class="poster"></div>
    </div>
    
    div.video {
      height: 50vh;
      background-color: red;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    div.poster {
        aspect-ratio: 16 / 9;
        background-color: yellow;
        max-height: 60%;
        max-width: 60%;
        height: 60%;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search