Search code examples
htmlcssalignmentvertical-alignmenttablecell

Why div align to left when change display property as table-cell?


HTML

<div class="table">
    <div class="table-cell">
        <div class="content">
            <div class="article">
                <h2>Title</h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            </div>
        </div>
    </div>
</div>

CSS

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

.table {
    width: 100%;
    height:100%;
    display:table;
}

.table-cell {
    display: table-cell;
    background-color:#ccc;
    vertical-align:middle;
    text-align:center;
}

.content {    
    background-color:#f00;
    width: 500px;
    height: 300px;
    margin:0 auto;
    text-align: left;
    color: #fff;
    display:table-cell;
    vertical-align: middle;
}

I want to align .content div as horizontally and vertically center in page. Also I want to align .article div as vertically center in .content div. But when I use table-cell property for .content div, it align to left. I want it as;

enter image description here

But it look like this;

enter image description here

http://jsfiddle.net/snu306fh/2/

Why and how can I fix?


Solution

  • Another option would be making .content a display: table and use .article as wrapper ( and adding display: table-cell to it )

    http://jsfiddle.net/snu306fh/6/

    .content {    
       background-color:#f00;
       width: 500px;
       height: 300px;
       margin:0 auto;
       text-align: left;
       color: #fff;
       display:table;
       vertical-align: middle;
    }
    
    .article {
       padding: 20px;
       display: table-cell;
    }
    

    Now I hope everyone happy?

    UPD: Mb this is what u actually looking for

    http://jsfiddle.net/snu306fh/11/

    If you add to .article vertical-align - you will get content of centered div - also to be centered

    .content {    
        background-color:#f00;
        width: 500px;
        height: 300px;
        margin:0 auto;
        text-align: left;
        color: #fff;
        display:table;
        vertical-align: middle;
    }
    
    .article {
        display: table-cell;
        vertical-align: middle;
        padding: 20px;
    }