In the below code snippet, the div elements (.main > div) are relatively positioned and are floated left.
Because of the relative positioning, the div elements (.main >
The reason is that each of your position:absolute;
elements are removed from the DOM's native flow, and positioned absolutely to their parent element. Since they both have the same positioning, they are placed over top of each other. Use position:relative
to position the elements relative to their native position in the DOM.
Your understanding is correct, though in this case where the div
's is floated, they will collapse into a width of 0, as none of the div
's has any normal flowing content, hence your absolute span
's overlap.
In below sample I gave the div
's a width, and now you can see it works how you expected.
html, body {
width: 100%;
height: 100%;
}
.main {
height: 5%;
border: 1px solid thistle;
}
.main > div {
position: relative;
float: left;
height: 100%;
border: 1px solid black;
width: 100px; /* added a width */
}
.main > div > span {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="main">
<div><span>Food</span></div>
<div><span>Health</span></div>
</div>
</body>
</html>