By making use of the :after pseudo-element and 'padding-bottom' , we can create our responsive square using only CSS. The solution relies on the somewhat counterintuitive fact that padding is calculated as a percentage of its parent element's width, not height.
But it's possible to make an element square if you use units like px or em to set both dimensions. Show activity on this post. A CSS only solution can be found here on the last "Resize with content" update. Although it applies for circles, you can remove the border-radius: 50% to make it work for squares.
if you set width:500px; and height:300px; (or whatever size you want) the div should stay the same size. Also, you can set overflow:hidden; so that if whatever is in the div goes beyond those bounds, it is not shown, and does not resize the div. Show activity on this post. Try this one.
Works on almost all browsers.
You can try giving padding-bottom
as a percentage.
<div style="height:0;width:20%;padding-bottom:20%;background-color:red">
<div>
Content goes here
</div>
</div>
The outer div is making a square and inner div contains the content. This solution worked for me many times.
Here's a jsfiddle
To achieve what you are looking for you can use the viewport-percentage length vw
.
Here is a quick example I made on jsfiddle.
HTML:
<div class="square">
<h1>This is a Square</h1>
</div>
CSS:
.square {
background: #000;
width: 50vw;
height: 50vw;
}
.square h1 {
color: #fff;
}
I am sure there are many other ways to do this but this way seemed the best to me.
HTML
<div class='square-box'>
<div class='square-content'>
<h3>test</h3>
</div>
</div>
CSS
.square-box{
position: relative;
width: 50%;
overflow: hidden;
background: #4679BD;
}
.square-box:before{
content: "";
display: block;
padding-top: 100%;
}
.square-content{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
color: white;
text-align: center;
}
http://jsfiddle.net/38Tnx/1425/
It is as easy as specifying a padding bottom the same size as the width in percent. So if you have a width of 50%, just use this example below
id or class{
width: 50%;
padding-bottom: 50%;
}
Here is a jsfiddle http://jsfiddle.net/kJL3u/2/
Edited version with responsive text: http://jsfiddle.net/kJL3u/394
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