• April 12, 2018

    For example, if I have a container with a child element like so:

    <div class="container">
        <div class="child">
        </div>
    </div>
    

    I can use the following css to give the child element an aspect ratio of 4:3

    .container { 
        width: 500px; /* pick whatever width you want */
    }
    .container .child {
        width: 100%;
        padding-top: 75%;
    }
    

    But, of course, if we put any content inside the child it will change the height and throw off our aspect ratio. So what we need is another element inside which is positioned absolutely over the child element which obtains its size. We do that like this:

    <div class="container">
        <div class="outer">
            <div class="inner">Your content</div>
        </div>
    </div>
    

    and css…

    .container { 
        width: 500px; /* pick whatever width you want */
    }
    .container .outer {
        width: 100%;
        padding-top: 75%; /* defines aspect ratio */
        position: relative;
    }
    .container .outer .inner {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }
    

    And that’s it! All in all, very intuitive solution that uses a counter intuitive feature of CSS.

    Here’s the full jsFiddle:

    http://wellcaffeinated.net/articles/2012/12/10/very-simple-css-only-proportional-resizing-of-elements



เวอไนน์ไอคอร์ส

ประหยัดเวลากว่า 100 เท่า!






เวอไนน์เว็บไซต์⚡️
สร้างเว็บไซต์ ดูแลเว็บไซต์

Categories