Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an element's width relative to its height?

Tags:

css

I know that it's possible to specify an element's height relative to its width, because percentage margin and padding values are calculated relative to its width. Is it possible to do the opposite - width relative to height?

like image 668
Oliver Zheng Avatar asked Jun 04 '12 06:06

Oliver Zheng


People also ask

How do you find the height and width of an element?

The width() method is used to check the width of an element. It does not check the padding, border and margin of the element. The height() method is used to check the height of an element but it will not check the padding, border and margin of the element.

How do I add height and width in HTML?

The height and width of an image can be set using height and width attribute. The height and width can be set in terms of pixels. The <img> height attribute is used to set the height of the image in pixels. The <img> width attribute is used to set the width of the image in pixels.


1 Answers

I found one way to do this without Javascript. Make an image with the ratio, and embed it into the HTML, scaling it accordingly, so that the parent element can inline-block fit to the image size.

<!-- height of the outer container -->
<div style="height: 200px">

    <!-- this will resize to 200px and maintain its aspect ratio --->
    <div style="display: inline-block; position: relative;">
        <img src="aspectratio.png" style="height: 100%; width: auto;" />
        <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0">
            <!-- Everything in here can party on the fact that their parent
                 has the correct aspect ratio -->
        </div>
    </div>

</div>
like image 96
Oliver Zheng Avatar answered Oct 31 '22 11:10

Oliver Zheng