The following matter occurs in Chr and FF on Win, and in Saf on iOS, so it's probably not a browser bug.
I have a #titleDiv inside a #container inside a #grandContainer. Here is the code (ignore the invalidated declarations for now):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Margin-top demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
}
body {
background-color: pink;
}
#grandContainer {
height: 100vh;
max-height: 1333px; /* The height of the background photo. */
max-width: 2000px; /* The width of the photo. */
margin: 0 auto; /* For the centering. Mind the margin-top: 0. */
background: url(https://www.freecodecamp.org/news/content/images/size/w2000/2021/07/kobu-agency-ipARHaxETRk-unsplash.jpg);
background-position: center center;
background-size: cover;
background-repeat: no-repeat;
over/flow: hidden;
/* Invalidated, the margin-top:100px of the #titleDiv is applied to the #grandContainer?? */
bor/der: 1px solid black; /* Ditto. */
}
#container {
over/flow: hidden; /* Ditto. */
bor/der: 1px solid black; /* Ditto. */
}
#titleDiv {
margin-top: 100px;
text-align: center;
font-size: 3em;
border: 1px dashed black;
}
</style>
</head>
<body>
<div id="grandContainer">
<div id="container">
<div id="titleDiv">Website Title</div>
</div>
</div>
</body>
</html>
And here is the matching Codepen: https://codepen.io/FrankConijn/pen/WNMWKGP.
As you can see, I gave the body a background: pink
and the titleDiv a margin-top: 100px
. I expected this:
To get the expected rendering, I had to give either the grandContainer or the container an overflow: hidden
(!) or a border
(revalidate one of the four by removing the slash in the Codepen). I know a thing or two about CSS, but why is that? There have been a number of questions asked and answered about collapsing margins, and I understand that principle. But this is different, as far as I can see.