Use CSS (and possibly JavaScript) to make the element square (or support a specific image format)

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

  • Width = 50% of its parent
  • A height equal to what is needed 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 from top to bottom to ensure that the object maintains the same aspect ratio.

I don't think you can use pure CSS for this, but does anyone know about this? Also, is there a simple JavaScript way? (JQuery is fine.)

+5
source share
4 answers

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

Set up your html structure as:

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

Use the transparent PNG AxB for rect_image, where AxB is the aspect ratio.

Meanwhile, set up a stylesheet, for example:

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

Of great importance here is that the images maintain aspect ratio when resizing in one direction. Meanwhile, we need a useful div, so we make the image display as a block, wrap it in a div and put an absolutely positioned div in it. I redid this code from something more complex that I really tested. It works like a charm.

+15
source

Here's the pure CSS version without the img tag:

<div class="apple_container"><div class="apple_icon"></div></div>

SCSS (including Compass for displaying background size):

.apple_container {
  width: 50%;
}
.apple_icon {
  padding-bottom: 100%;
  background-image: url(/images/apple.png);
  background-repeat: no-repeat;
  @include background-size(contain);
  background-position: center center;
}

CSS created from the above:

.apple_container {
  width: 50%;
}
.apple_icon {
  padding-bottom: 100%;
  background-image: url(/images/apple.png);
  background-repeat: no-repeat;
  -webkit-background-size: contain;
  -moz-background-size: contain;
  -o-background-size: contain;
  background-size: contain;
  background-position: center center;
}

, . , .

+4

jQuery sounds pretty easy. Set the width to 50% in CSS, and then the following:

function onResize() {
    var el = $('#element');
    el.height(el.width());
}
$(window).resize(onResize);
$(document).ready(onResize);
+3
source
0
source

All Articles