Center div without negative margins
I have a jsfiddle here: http://jsfiddle.net/apej60nL/
I have two columns in bootstrap. One column has text as content, the other is empty except for the yellow div that displays the image.
I need to center the yellow div vertically against a text block. For this, I need to make the left div containing a yellow div the same height as the text div.
I did it with
.test .row {
display: table;
}
.left, .right {
float: none;
display: table-cell;
vertical-align: top;
}
I positioned the yellow div absolutely and used negative margins to center it. I can do this because I know the width / height of the yellow div. I need to do this without knowing the width / height. The image / div can be of different sizes.
How can I center it vertically, knowing the size?
source to share
I've made a few changes to your CSS to achieve what you're looking for:
.left, .right {
float: none;
display: table-cell;
//deleted vertical-align: top;
}
.left{
background: red;
vertical-align:middle; //replaced position: relative; with this
}
.right{
vertical-align: top; //add this
background: #ddd;
}
.block{
//various changes here, will be centered horizontally and vertically
background: yellow;
margin-left: auto;
margin-right: auto;
text-align: center;
}
JS Fiddle Demo
Note. If you want to constrain the block
div width , add style max-width
.
source to share
vertical-align: middle
works fine with table cells, but I had to change the yellow block to display: inline-block
:
.test .row {
display: table;
}
.left, .right {
float: none;
display: table-cell;
}
.left {
background: #F00;
vertical-align: middle;
text-align: center;
}
.right {
background: #DDD;
vertical-align: top;
}
.block {
background: #FF0;
display: inline-block; /* display changed to inline block */
text-align: left; /* text align is inherited so reset it */
}
source to share