Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CSS (and maybe JavaScript) to make an element be square (or maintain a specific aspect ratio)

I have a div that I want to have the following characteristics:

  • Width = 50% of its parent element
  • Height equal to whatever it needs to be in order to maintain a certain aspect ratio.

I need to use percentages because the object will resize left-right when the browser is resized. I want the object to be resized top-bottom to ensure the object maintains the same aspect ratio.

I don't think there's any way to use pure CSS to do this, but does anyone know of a way? Alternatively, is there an easy JavaScript way to do this? (JQuery is fine.)

like image 902
David Pfeffer Avatar asked Jan 14 '10 17:01

David Pfeffer


People also ask

How do you maintain aspect ratio in CSS?

In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do I change the aspect ratio of an image in CSS?

Using padding-top to set the height from width. Using position: absolute to put image in the padding space. Using max-height and max-width to make sure the image will not over the parent element. using display:block and margin: auto to center the image.


1 Answers

I figured out how to do this without js, though you need to use a transparent image.

Set up a html structure like:

<div class="rect_container"><img class="rect_image" src="rect_image.png"/>
 <div class="rect">Your favorite content here</div>
</div>

Use a AxB transparent png for rect_image where AxB is the aspect ratio.

Meanwhile set up a stylesheet like:

.rect_container {width: 50%; position: relative;}
.rect_image {width: 100%; display: block;}
.rect {width: 100%; height: 100%; position: absolute; left: 0px; top: 0px;}

The important thing here is taking advantage of the fact that images maintain their aspect ratio when resized in one direction. Meanwhile, we need a useable div, so we make the image display as block, wrap it in a div, and put an absolutely positioned div inside that. I distilled this code from something more complicated I actually tested. Works like a charm.

like image 140
Joe Avatar answered Oct 21 '22 08:10

Joe