Reputation: 4218
This is what my code looks like.
#container {
width: 584px;
height: 50px;
position: relative;
overflow: hidden;
}
#container ul {
position: absolute;
margin: 0;
padding: 0;
width: 3504px;
}
#container ul li {
width: 584px;
float: left;
margin: 0;
padding: 0;
overflow: hidden;
}
<div id="container">
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
</div>
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 and trying to find a way, but everything seems to collide with the rules I already have.
Any idea how to do this?
Would it help if instead of the #container
div I used a table with one row and column?
Upvotes: 10
Views: 33752
Reputation: 60923
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*/
}
.container ul{
background:#00f;
}
<div class="container">
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
</div>
Upvotes: 4
Reputation: 65
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.
Upvotes: 0
Reputation: 24988
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:
<div class="container">
<div class="helper">
<ul><!--stuff--></ul>
</div>
</div>
http://jsfiddle.net/ovfiddle/yVAW9/
Upvotes: 9
Reputation: 7310
"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).
Upvotes: 4
Reputation: 738
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 UL
var ulheight = $("#container ul li")[0].scrollHeight;
// Based on the height of the container being 50px you can position the UL accordingly
var pushdown = (50-ulheight)/2;
$("#container ul li").css("top", pushdown);
});
Upvotes: 0