Question

I have the table, inside the table I have another box , I am struggling to align the box in center of the table.

My CSS code is

Inside box code

.inside_box{
border: medium solid;
display: table-cell;
float: none;
font-family: Helvetica-bold;
font-size: 20.19px;
height: 100px;
margin: auto;
text-align: center;
vertical-align: middle;
width: 300px;
}

Outside table CSS:

.outer_table {
    border: 1px solid black;
    border-radius: 5px;
    color: #1A6DAC;    
    font-size: 24px;
    left: 40px;
    padding: 20px;
    position: absolute;
    top: 260px;
    width: 740px;
}

enter image description here

How to align the inside box in center?

Was it helpful?

Solution

I assume that your HTML is something like this

<div class="outer_table">
    <div class="inside_box">hello world</div>
</div>

So, you are using display: table-cell; for .inside_box and margin: auto; won't work, as it's a table cell now, so what you can do is, wrap a div around hello world text, like this

Demo

<div class="outer_table">
    <div class="inside_box"><div>hello world</div></div>
</div>

And use CSS like

.inside_box {
    border: medium solid;
    display: table;
    font-family: Helvetica-bold;
    font-size: 20.19px;
    height: 100px;
    margin: auto;
    width: 300px;
}
.outer_table {
    border: 1px solid black;
    border-radius: 5px;
    color: #1A6DAC;
    font-size: 24px;
    left: 40px;
    padding: 20px;
    position: absolute;
    top: 260px;
    width: 740px;
}

.inside_box > div {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

Make sure you port the text-align: center; and vertical-align: middle; properties from .inside_box to .inside_box > div selector block.


Note: You won't need float: none;, not sure why you are using that.


As I got a comment, that what if you do not want to add an extra div element, so think like that you are using td without a table tag. So there is no way for that div with display: table-cell; to respect margin: auto;.

From Mozilla Developer Network :

enter image description here

OTHER TIPS

Try to change and make your css like this:

.outer_table td {
text-align: center; // Align center
}

.inside_box {
float: none; // if you set float left or right your box will move right there
margin: 0px auto; // this setting for balancing margin left and right
}



<table class="outer_table">
<tr><td><div class="inside_box">Hellow wolrd!</div></td></tr>
</table>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top