1

I'm trying to create a div and keeping its aspect ratio to 16 : 9 using css. I made a google search, and quickly found this: How to maintain the aspect ratio. So I tried doing it myself, but came upon a problem. When I add text inside, the ratio changes, and isn't 16 : 9 ratio anymore.

JSFiddle

When you remove all the li's, then the ratio is correct. How can I keep the aspect ratio even when adding text inside?

Code Snippet:

div {
    width: 70%;
}
ul {
    padding-bottom: 56.25%;
    background: green;
}
<div>
<ul>
 <li>1</li>
 <li>2</li>
 <li>3</li>
 <li>4</li>
</ul>
</div>
Community
  • 1
  • 1
Jessica
  • 9,379
  • 14
  • 65
  • 136

2 Answers2

1
  1. Build a div that has the wanted aspect ratio, with the padding-technique described in the link you gave.
  2. Make that div positioned relative, absolute or fixed, and add a child element into it. Make this child positioned absolute, with top, bottom, left and right set to 0. The child will always have the same aspect ratio the outer div has, no matter what its content is.
  3. If you need it, set overflow:hidden on the inner element.

HTML:

<div class="outer">
    <ul class="inner">
        <li>List items go here</li>
        <li>...</li>
    </ul>
</div>

CSS:

.outer {
    padding-bottom: 56.25%; // 9/16
    position: relative; // or absolute or fixed, but not static
}

.inner {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    overflow: hidden; // or scroll, auto
}
Jost
  • 5,948
  • 8
  • 42
  • 72
0

You need to make your ul absolutely positioned within your green div so it will not affect your padding. Here's the CSS you need:

div {
    width: 70%;
    position: relative;
}
ul {
    padding-bottom: 56.25%;
    background: green;
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
}
MW5280
  • 16
  • 1