Let's say I've got a div that has a width of 50% of the body. How do I make its height equal to that value? So that when the browser window is 1000px wide, the div's height and width are both 500px.
This question is related to
css
<div><p>some unnecessary content</p></div>
div{
border: 1px solid red;
width: 40%;
padding: 40%;
box-sizing: border-box;
position: relative;
}
p{
position: absolute;
top: 0;
left: 0;
}
For this to work i think you need to define the padding to ex. top? like this:
<div><p>some unnecessary content</p></div>
div{
border: 1px solid red;
width: 40%;
padding-top: 40%;
box-sizing: border-box;
position: relative;
}
p{
position: absolute;
top: 0;
left: 0;
}
anyways, thats how i got it to work, since with just padding all arround it would not be a square.
I made a CSS approach to this that is sized by the viewport width, but maxes out at 100% of the viewport height. It doesn't require box-sizing:border-box
. If a pseudo element cannot be used, the pseudo-code's CSS can be applied to a child. Demo
.container {
position: relative;
max-width:100vh;
max-height:100%;
margin:0 auto;
overflow: hidden;
}
.container:before {
content: "";
display: block;
margin-top: 100%;
}
.child {
position: absolute;
top: 0;
left: 0;
}
Support table for viewport units
I wrote about this approach and others in a CSS-Tricks article on scaling responsive animations that you should check out.
This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box
CSS attribute:
div {_x000D_
border: 1px solid red;_x000D_
width: 40%;_x000D_
padding: 40%;_x000D_
box-sizing: border-box;_x000D_
position: relative;_x000D_
}_x000D_
p {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
}
_x000D_
<div>_x000D_
<p>Some unnecessary content.</p>_x000D_
</div>
_x000D_
Adjust percentages to your liking. Here is a JSFiddle
Source: Stackoverflow.com