Skip to content Skip to sidebar Skip to footer

Vertically Center Ul In Div

This is what my code looks like. As the title says, I want to center the ul vertically inside the div. I cannot change the above CSS rules because. I've been googling solutions an

Solution 1:

Please use the search function in the future. The full answer is explained here; this is the code for your scenario:

.container {
  display: table;
  height: 100%;
  position: absolute;
  overflow: hidden;
  width: 100%;}
.helper {
  #position: absolute; /*a variation of an "lte ie7" hack*/#top: 50%;
  display: table-cell;
  vertical-align: middle;}
ul{
  #position: relative;
  #top: -50%;
  margin:0 auto;
  width:200px;}

The three elements have to be nested like so:

<divclass="container"><divclass="helper"><ul><!--stuff--></ul></div></div>

http://jsfiddle.net/ovfiddle/yVAW9/

Solution 2:

"Centring" a div or other containers vertically is quite tricky in CSS, here are your options.

You know the height of your container

If you know the height of the container, you can do the following:

#container {
    position: absolute;
    top: 50%;
    margin-top: -half_of_container_height_here;
}

So we essentially place in the middle and then offset it using a negative margin equal to the half of the height. You parent container needs to have position: relative.

You don't know the exact height of your container

In this case you need to use JavaScript and calculate the appropriate margins (unfortunately you cannot use margin-top: auto or something similar).

More info here.

Solution 3:

You can use flex to make your ul center vertical, horizontal or both like

.container{
  background:#f00;
  height:150px;
  display:flex;
  align-items:center;
  /*justify-content:center;=>will make ul center horizontal*/
}
.containerul{
  background:#00f;
}
<divclass="container"><ul><li>A</li><li>B</li><li>C</li></ul></div>

Solution 4:

If you can add jQuery library you could try this,

$(document).ready(function(){

    // Remove li float
    $("#container ul li").css("float", "none");

    // Get the full height of the ULvar ulheight = $("#container ul li")[0].scrollHeight;

    // Based on the height of the container being 50px you can position the UL accordinglyvar pushdown = (50-ulheight)/2;
    $("#container ul li").css("top", pushdown);

});

Solution 5:

Now you can make the parent container display:flex and align-items:center. That should work. Although flexbox properties are not supported by older browsers.

Post a Comment for "Vertically Center Ul In Div"