I'm trying to figure out a way to vertically center an unordered list within a div. I found a number of ways to do this, however the li tags within my ul tag have PHP code in them that gets text from a database and this causes the length of the text within the li tags to vary in length significantly causing vertical sifting within my div which has a fixed height and width.
How can I vertically position my unordered list so it'll always be vertically aligned within this div?
To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element. Now, add the style to the div class and use the text-align property with center as its value.
Just give the list centered text (e.g. ul. nav { text-align: center; } ) and the list items inline-block (e.g. ul. nav li { display: inline-block; } ). If you want to do it with margin for whatever reason, look into width: fit-content; .
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
If you're trying to center horizontally, here is a bit of code that will work for any length:
Preview: http://jsfiddle.net/Wexcode/6UtFz/
HTML:
<div>
<ul>
<li><a href="#">Element 1</a></li>
<li><a href="#">Element 2</a></li>
<li><a href="#">Element 3</a></li>
<li><a href="#">Element 4</a></li>
</ul>
</div>
CSS:
div { overflow: hidden; }
ul {
position: relative;
float: left;
left: 50%;
padding: 0;
list-style: none; }
li {
position: relative;
float: left;
right: 50%;
margin: 0 5px; }
For vertical-centering, just make use of the vertical-align
property.
See: http://jsfiddle.net/Wexcode/fK793/
It's pretty simple. Just use display:table;
for the parent div and display:table-cell;
and vertical-align:middle;
for the child.
Fiddle: https://jsfiddle.net/fzfa312m/
div {
background: #f2f2f2;
width: 300px;
height: 300px;
display:table; }
ul {
vertical-align: middle;
display: table-cell; }
<div>
<ul>
<li><a href="#">Element 1</a></li>
<li><a href="#">Element 2</a></li>
<li><a href="#">Element 3</a></li>
<li><a href="#">Element 4</a></li>
</ul>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With