Reputation: 12512
I have a container and an element withing it.
<div id="container">
<div class="myEm">
...
</div>
</div>
I need to assign width and hight to that element. It should be a square. I can calculate the width relative to the parent container, but how do I pass the same value to the height:
#container .myEm {
width: calc(100% - 20px);
height: ???
}
Upvotes: 2
Views: 16263
Reputation: 4936
You can save yourself the wrapping div by using pseudo elements.
This solution will create the same effect – but also make the div stretch to fit content – should it become too large to be contained by the square.
/* sane box-sizing */
html { box-sizing: border-box; }
*, *::before, *::after { box-sizing: inherit; }
/* box styling */
.box {
margin: 10px;
padding: 10px;
width: calc(100% - 20px);
background-color: tomato;
font-size: 10px;
float: left;
max-width: 150px;
}
/* ––––––––––––––––––––––––––––––––––––-
This is the aspect ratio part
––––––––––––––––––––––––––––––––––––- */
.box::before {
/* aspect ratio keeper – 100% = square */
padding-bottom: 100%;
float: left;
}
.box::before,
.box::after {
content: '';
display: table;
clear: both;
}
/* second box */
.box:nth-of-type(2) { background-color: olive; }
<div class="box">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita labore iusto vero perspiciatis ex fuga natus cum molestiae ut, dolor facere maxime voluptatem nesciunt nihil repellendus culpa eligendi laudantium velit.</p>
</div>
<div class="box">
<h2>Will stretch to content</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita labore iusto vero perspiciatis ex fuga natus cum molestiae ut, dolor facere maxime voluptatem nesciunt nihil repellendus culpa eligendi laudantium velit. Expedita labore iusto vero perspiciatis ex fuga natus cum molestiae ut, dolor.</p>
</div>
Upvotes: 0
Reputation: 2629
One way is to make the myEm
resize using padding bottom (or top) to maintain its aspect ratio. This makes myEm
strictly a sizing element and you'll need an element inside that will size to itself. Here's what I mean for example:
myEm
becomes:
.myEm {
height: 0;
padding-bottom: calc(100% - 20px);
position: relative;
width: calc(100% - 20px);
}
Then you need an element inside with the actual content:
.myEm-inner {
background: red;
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 0;
}
Example: https://jsfiddle.net/dgmyxs9v/1/
Upvotes: 1