简体   繁体   中英

CSS – Header in display: table element – positioning issue

While creating a HTML layout, I noticed some strange positioning issue I was unable to solve.

Take the following HTML:

<div class="outer-wrap">
<div class="header">
    I am a Header
</div>
<div class="element">
    Hello world
</div>

And combine with this CSS code:

@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;
}

Fiddle

As you can see, I've set the wrapper to display: table , which enables me to vertically center any child element with setting display: table-cell and vertical-align: middle .

Now when I try to add a header, strange things start to happen.

First, I have to declare position: absolute on the header, otherwise the header horizontally pushes away .element . I don't know why this happens, but I understand why this fix works: Because position: absolute takes things 'out of the flow'.

But if I take a look at the Fiddle, you'll notice a small gap on the left side which exposes the grey background color defined on .outer-wrap :

在此处输入图片说明

What is causing this gap & how to fix this?
Why do I have to use absolute positioning on the header to make it expand to the full container width?

The key reason causing that is you're not defining the table-cell div and would not be 100% wide and you see its shifting towards right seeing the gray border color which is the background of outer-wrap div. So, you need to define the width:100%; when you use display:table-cell; to make it display correctly.

Changed css:

.outer-wrap {
    width: 100%;
    height: 100%;
    display: table;
    background: grey;
}

.element {
    display: table-cell;
    vertical-align: middle;
    background: blue;
    width: 100%;/*explicitly define width to be 100%*/
}

.header {
    position: absolute;
    background: red;
    z-index: 1;/*to make it display in front*/
}

Fixed fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM