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?

+3


source to share


5 answers


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

.

+1


source


Make the top / right / bottom / left position of the yellow box (image) zero and the auto margin value:

.block {
    background: yellow;
    position: absolute;
    height: 150px;
    top: 0;
    left: 0;
    bottom:0;
    right:0;
    margin:auto;
    width: 50px;
}

      



JsFiddle example

+4


source


Without knowing the width / height, here's an example:

.block{
    background: yellow;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%)
    transform: translate(-50%,-50%)
}

      

Demo

+2


source


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 */
}

      

Updated Fiddle

+1


source


see it.

$(document).ready(function(){
    var l=$('.left').height()-50;
    var t=l/2;
    $('.block').css('top',t);
});

      

http://jsfiddle.net/srvnk44/apej60nL/22/

+1


source







All Articles