All my life I thought that a div expands to the size of its content unless its dimensions are explicitly set or are limited.
html and body have no size limit – stretch as much as you want.
I would like to understand since when did the logic change and it expands to the size of viewPort?
Am I wrong or is this a bug?
style.css
html, body {
margin: 0; padding: 0;
}
html {
height: 100%;
}
body {
min-height: 100%;
}
example.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="strangeSize"> <!-- It's will have size of viewPort -->
<div id="wideContent" style="width: 5000px; height: 200px; background: red;"></div>
</div>
</body>
</html>
I await #strangeSize width equal 5000px, but it was been equal viewPort width.
Why is this a problem? If want to make an overlay over the div/image, we will not cover it completely.
#overlay {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.2);
}
.point {
position: absolute;
font-size: 10px;
font-family: sans-serif;
display: flex;
align-items: center;
justify-content: center;
width: 20px; height: 20px;
border-radius: 20px;
border: 2px Solid Black;
background: white;
box-sizing: border-box;
margin: -10px 0 0 -10px;
}
<div id="strangeSize" style="position: relative;">
<div id="wideContent" style="width: 5000px; height: 200px; background: red;"></div>
<div id="overlay">
<div class="point" style="top: 80px; left: 2100px;">1</div>
<div class="point" style="top: 100px; left: 2200px;">2</div>
<div class="point" style="top: 120px; left: 2300px;">3</div>
</div>
</div>
I found the solution – for #strangeSize using width: fit-content;
fixes that. That solution relative fresh because full support of fit-content was available since end of 2021. But why we have this alogic behavor???
Петров Павел is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.