Recently, I was preparing for an interview, and I was asked a frequent question about layout, “How can I make div height always be half the width with CSS?”
Let’s take a look at some of the possible implementations, and what the pros and cons of each approach are:
First: VW units
The HTML code
<div class="container">vw</div>
Copy the code
Style style
.container {
width: 100vw;
height: 50vw;
background: green;
}
Copy the code
rendering
Pros and cons: The advantage is that it only requires VW units, the disadvantage is that VW units contain scroll bar width
Vw +var+calc
The HTML code
<div class="box">var + calc + vw</div>
Copy the code
Style style
:root {
--wwidth: 100vw;
--hheight: calc(var(--wwidth) / 2);
}
.box {
width: var(--wwidth);
height: var(--hheight);
border: 1px solid red;
display: flex;
align-items: center;
justify-content: center;
color: green;
font-size: 30px;
}
Copy the code
rendering
Pros and cons: The cons are that VW units include scrollbar widths, the pros are that custom units can be as wide as they want
The third kind: padding
The HTML code
<div class="outer">
<div class="inner">padding</div>
</div>
Copy the code
Style style
.outer {
width: 100%;
/*padding-bottom: 50%; * /
padding: 25% 0;
position: relative;
}
.inner {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 30px;
background: skyblue;
}
Copy the code
rendering
Pros and cons: The advantage is that the width is 100% and the scrollbar is not included. The disadvantage is that it requires two HTML tags to implement
This article is the author summarizes the compilation, if there is bias, welcome to leave a message correction, if you think this article is useful to you, might as well point a thumbs-up ~
About the author:
GitHub simple book nuggets