Reputation: 145
HTML :
<nav>
<ul>
<li><a href="Index">Home</a></li>
<li><a href="History">History</a></li>
<li><a href="Appointments">Appointments</a></li>
<li><a href="Contactus">Contact us</a></li>
</ul>
</nav>
CSS :
nav {
position: relative;
margin: auto;
padding: 0;
list-style: none;
width: 100%;
display: center;}
nav ul li {
display: inline;
}
nav ul li a {
display: inline-block;
text-decoration: none;
padding: 5px 0;
width: 100px;
background: #Cc3399;
color: #eee;
float: left;
text-align: center;
border-left: 1px solid #fff;
}
nav ul li a:hover {
background: #a2b3a1;
color: #000
}
Basically, I've managed to make this navigation bar, that fits my specifications. However, it's not centered, it's in position vertically, but horizontally it's way left and no where near the center of the page.
Upvotes: 2
Views: 5311
Reputation: 1701
to horizontally center an element, this element needs to be display:block; and it should have a width that is less than 100%
Here is the css, slight modification based on what you have
nav {
position: relative;
/*** centers the nav block ****/
margin-left: auto;
margin-right: auto;
width: 80%;
}
nav ul{
padding: 0;
list-style: none;
}
nav ul li {
display: inline;
}
nav ul li a {
display: inline-block;
text-decoration: none;
padding: 5px 0;
width: 20%; /*** make the centering look more vivid ****/
background: #Cc3399;
color: #eee;
float: left;
text-align: center;
border-left: 1px solid #fff;
}
nav ul li a:hover {
background: #a2b3a1;
color: #000
}
You can view it on jsfiddle
Upvotes: 0
Reputation: 937
Since you have given margin as 100% for it will not have impact on margin.. So try giving 50% width to and it should work. You can change like this...
nav
{
position: relative;
margin: auto;
padding: 0;
list-style: none;
width: 50%;
display: center;
}
Upvotes: 0
Reputation: 33228
One solution is to replace inline
to inline-block
and use text-align: center
to parent(also display: center
is not valid css):
nav {
position: relative;
margin: auto;
padding: 0;
list-style: none;
width: 100%;
text-align: center;/*add text align-center*/
}
nav ul li {
display: inline-block;/*replace inline to inline-block*/
}
nav ul li a {
display: inline-block;
text-decoration: none;
padding: 5px 0;
width: 100px;
background: #Cc3399;
color: #eee;
float: left;
text-align: center;
border-left: 1px solid #fff;
}
nav ul li a:hover {
background: #a2b3a1;
color: #000
}
<nav>
<ul>
<li><a href="Index">Home</a>
</li>
<li><a href="History">History</a>
</li>
<li><a href="Appointments">Appointments</a>
</li>
<li><a href="Contactus">Contact us</a>
</li>
</ul>
</nav>
Upvotes: 5