Why display: table doesn't center div?

.headers
{
    background-color: #ff0000;
    width: 100%;
    overflow: hidden;
    display: table;
}
.logo
{
    height: 35px;
    border: 1px solid #00ff00;
    float: left;
    width: 30px;
}
.slogan
{
    float: right;
    display: table-cell;
    vertical-align: middle;
}
      

<div class="headers">
    <div class="logo"></div>
    <div class="slogan">IIN</div>
</div>
      

Run codeHide result


How can I center my div [slogan] without using negative margin / top 50%?

+3


source to share


4 answers


you don't need it float

when using display: table/table-cell

... this should center the div .slogan

with the layout table-cell

.



.headers
{
    background-color: #ff0000;
    width: 100%;
    overflow: hidden;
    display: table;
}
.logo
{
    height: 35px;
    border: 1px solid #00ff00;
    /*float: left; NOT THIS */
    width: 30px;
    display: table-cell; /* THIS */
}
.slogan
{
    /*float: right; NOT THIS */
    display: table-cell;
    vertical-align: middle;
    text-align: right; /* THIS */
}
      

<div class="headers">
    <div class="logo"></div>
    <div class="slogan">IIN</div>
</div>
      

Run codeHide result


+4


source


If you are looking at the middle vertical slogan please check the fiddle https://jsfiddle.net/nileshmahaja/e6byt6zt/

CSS



.headers
{
    background-color: #ff0000;
    width: 100%;
    overflow: hidden;
    display: table;
    vertical-align:middle;
}
.logo
{
    height: 35px;
    border: 1px solid #00ff00;
    float: left;
    width: 30px;
}
.slogan
{
    display: table-cell;
    vertical-align: middle;
    text-align:right;
}

      

+1


source


change your slogan class to

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

      

+1


source


You must use 'margin: 0 auto;' on the. If you want to align the text inside the div, you can simply use "text-align: center;".

Check this post click

0


source







All Articles