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.
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 .
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With