Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

div's height = its width, in percentages, so that the div looks like a square, with non-square shape of the container element (CSS only)

Tags:

html

css

I have set my elements' widths and heights in percentages so that they look a little bigger on bigger screens and normal on normal ones. I have also set min-height and min-width so that the layout isn't distorted when viewing on a screen too small. I want one of my elements to appear as a square, but I am unable to come up with a CSS-only solution for it to happen.

Here is what I tried: http://jsfiddle.net/5VTTD/, but it didn't work.

This works: http://jsfiddle.net/5VTTD/1/, but it uses JS.

like image 474
Peeyush Kushwaha Avatar asked Oct 08 '12 12:10

Peeyush Kushwaha


People also ask

How does percentage height work CSS?

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto .

When you set the width and height properties of an element with CSS you just set the width and height of the?

Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.


1 Answers

You will need an external <div> as a container and then an internal one as a square.

I used 50% dimensions for the square, but you can use the size you desire: it will be relative to the parent <div> container.

I also gave it a black background color to highlights it: here there is a DEMO.

The trick is all in the padding-bottom: 100% of the parent <div>.

CSS:

#container {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
}

#square {
  position: absolute;
  width: 50%;
  height: 50%;
  background-color: #000000;
}

HTML:

<div id="container">
  <div id="square">
  </div>
</div>
like image 134
Cirou Avatar answered Nov 15 '22 06:11

Cirou