Why is width: 100% not working on div {display: table-cell}?

timshutes picture timshutes · Jul 19, 2013 · Viewed 109.9k times · Source

I'm trying to vertically and horizontally center some content overlaying an image slide (flexslider). There were some similar questions to this one, but I couldn't find a satisfactory solution that applied directly to my specific problem. Because of the limitations of FlexSlider, I cannot use position: absolute; on the img tag in my implementation.

I almost have workaround below working. The only problem is I cannot get the width & height declarations to work on inner-wrapper div with the display: table-cell property.

Is this standard behavior, or am I missing something with my code? If it's standard behavior, what's the best solution to my problem?

HTML

<ul>
    <li>
        <img src="#">
        <div class="outer-wrapper">
            <div class="inner-wrapper">
                <h1>My Title</h1>
                <h5>Subtitle</h5>
            </div>
        </div>
    </li>
</ul>

CSS

html, body {
    margin: 0; padding: 0;
    width: 100%; height: 100%;
}

ul {
    background: #CCC;
    height: 100%;
    width: 100%;
    list-style-position: outside;
    margin: 0; padding: 0;
}

li {
    width: 100%;
    display: table;
}

img {
    width: 100%;
    height: 410px;
}

.outer-wrapper {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    margin: 0; padding: 0;
}

.inner-wrapper {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 100%;
    height: 100%;
}

Note: the centered content will be more than 1 element, so I can't use the line-height trick.

jsFiddle.

Answer

woojoo666 picture woojoo666 · Jul 19, 2013

Putting display:table; inside .outer-wrapper seemed to work...

JSFiddle Link


EDIT: Two Wrappers Using Display Table Cell

I would comment on your answer but i have too little rep :( anyways...

Going off your answer, seems like all you need to do is add display:table; inside .outer-wrapper (Dejavu?), and you can get rid of table-wrapper whole-heartedly.

JSFiddle

But yeah, the position:absolute lets you place the div over the img, I read too quickly and thought that you couldn't use position:absolute at all, but seems like you figured it out already. Props!

I'm not going to post the source code, after all its 99% timshutes's work, so please refer to his answer, or just use my jsfiddle link

Update: One Wrapper Using Flexbox

It's been a while, and all the cool kids are using flexbox:

<div style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
    stuff to be centered
</div>

Full JSFiddle Solution

Browser Support (source): IE 11+, FireFox 42+, Chrome 46+, Safari 8+, iOS 8.4+ (-webkit- prefix), Android 4.1+ (-webkit- prefix)

CSS Tricks: a Guide to Flexbox

How to Center in CSS: input how you want your content to be centered, and it outputs how to do it in html and css. The future is here!