During my HTML layout creation process, I encountered a peculiar positioning issue that proved difficult to resolve.
Consider the following HTML structure:
<div class="outer-wrap">
<div class="header">
I am a Header
</div>
<div class="element">
Hello world
</div>
Now, merge it with this CSS snippet:
@import "https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.css";
html, body { height: 100%; }
.outer-wrap {
width: 100%;
height: 100%;
display: table;
background: grey;
}
.element {
display: table-cell;
vertical-align: middle;
background: blue;
}
.header {
position: absolute;
background: red;
}
By setting the wrapper's display property to table
, I managed to vertically center any child element by simply using display: table-cell
and vertical-align: middle
.
However, issues arose when attempting to add a header component.
To prevent the header from horizontally pushing away the .element
, I had to apply position: absolute
to the header - although I'm not entirely sure why. This fix works because position: absolute
removes elements from the flow of the document.
If you examine the Fiddle closely, you'll notice a small gap on the left side revealing the grey background color defined in the .outer-wrap
:
What could be causing this gap and how can it be resolved?
Why is it necessary to use absolute positioning on the header for it to expand to the full container width?