Joel B Joel B - 5 months ago 7
CSS Question

Centering a list item in an unordered list

I've been bashing my head against a wall for too long trying to figure this one out.

I'm building a responsive site for my blog. The navbar is composed of an

<ul>
with 6
<li>
's. 5 of them display on a full-size screen. The navicon appears and other list items disappear when the screen is scaled down to mobile size. For some reason I can't get the navicon(hamburger icon) to appear in the center of the screen. I'm trying to avoid centering it using position: relative.


/*Reponsive CSS*/

@media only screen and (max-width: 500px) {

#navbar nav a {
display: none;
}

#navbar nav a.menu-icon {
display: block;
font-size: 35px;
padding: 30px 30px;
}

#navbar nav a.menu-icon:hover {
text-decoration: none;
}


}

<aside>
<div id="navbar">
<nav>
<ul>
<li><a href="/">Item 1</a></li>
<li><a href="blank.html">Item 2</a></li>
<li><a href="blank.html">Item 3</a></li>
<li class="pull-right"><a href="blank.html">Item 4</a></li>
<li class="pull-right"><a href="blank.html">Item 5</a></li>
<li><a href="#" class="menu-icon">&#9776;</a></li><!--On a mobile device this is the only list item displaying -->
</ul>
</nav>
</div>
</aside>





current version

Answer

You can center elements or text nodes by setting text-align:center; or you can center block elements by applying margin-left: auto; margin-right: auto; on the element itself.

In this case the <li> and its <a> are spanning the entire width of their parent, its just the text inside the <a> that its not centered. So you would have to apply text-align: center; to the .menu-icon class

/*Reponsive CSS*/

@media only screen and (max-width: 500px) {

#navbar nav a {
	display: none;
}

#navbar nav a.menu-icon {
    display: block;
    font-size: 35px;
    padding: 30px 30px;
    text-align: center;
}

#navbar nav a.menu-icon:hover {
	text-decoration: none;
}


}
<aside>
	<div id="navbar">
		<nav>
			<ul>
				<li><a href="/">Item 1</a></li>
				<li><a href="blank.html">Item 2</a></li>
				<li><a href="blank.html">Item 3</a></li>
				<li class="pull-right"><a href="blank.html">Item 4</a></li>
				<li class="pull-right"><a href="blank.html">Item 5</a></li>
				<li><a href="#" class="menu-icon">&#9776;</a></li><!--On a mobile device this is the only list item displaying -->
			</ul>
		</nav>
	</div>
</aside>

Comments