Reputation: 177
I have no formal training in HTML and CSS, but web development is a hobby of mine, and I have a problem that I am really struggling to get for my personal website. Here:
You can see that the elements of my unordered list are not centred on the black unordered list background; in the body
tag:
<ul>
<li><a href="homepage.html">Home</a></li>
<li><a href="resume.html">Bio</a></li>
<li><a href="projects.html">Projects</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="store.html">Store</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
Previously, in the head
tag, I declare the style for each of these elements in the document, and what to do if the cursor hovers over it:
<style>
ul {
list-style-type: none;
background-color: black;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
border-width: thick;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color: darkgray;
}
</style>
The concept I've tried more times than not is if you have a div
tag around li
and you centre that. But, I am going in circles. So how do you centre the white lettering while keeping an equal amount of black space on either side? Thank you very much!
For reference, I have branched out from this tutorial.
Upvotes: 0
Views: 47
Reputation: 8650
By default, ul
and li
are display: block;
. In order to achieve your result you need to wrap your list in a centered div and set the background color on the div.
Add a wrapper to your HTML
<div class="wrapper">
<ul>
<li><a href="homepage.html">Home</a></li>
<li><a href="resume.html">Bio</a></li>
<li><a href="projects.html">Projects</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="store.html">Store</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
Then, in your CSS
.wrapper {
background-color: black;
text-align: center;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
display: inline-block;
}
Upvotes: 1
Reputation: 108
You can use flexbox with justify-content: center;
For example
ul {
list-style-type: none;
background-color: black;
margin: 0;
padding: 0;
overflow: hidden;
display: flex;
justify-content: center;
}
Upvotes: 1
Reputation: 278
Add a div wrapper to ul element:
<div class="ul-wrapper">
<ul>
<li><a href="homepage.html">Home</a></li>
<li><a href="resume.html">Bio</a></li>
<li><a href="projects.html">Projects</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="store.html">Store</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
And then set styles for div like this:
.ul-wrapper {
text-align: center;
background-color: black;
}
And add display: inline-block; to ul styles.
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
display: inline-block;
}
Upvotes: 1