I am trying to create a navigation menu with a total of 5 link to other pages.
I cannot figure out how to make the text span from one end to the other, so it takes the whole width of the page, and in the same time is flexible.
The structure is very simple:
ul {
display: flex;
justify-content: center;
width: 100%;
}
ul li {
display: inline-block;
text-align: center;
flex: 1;
justify-content: space-between;
}
ul li a {
display: inline-block;
width: 100%;
font-size: 16px;
font-weight: 300;
color: #070707;
}
<ul>
<li><a href="">Contact us</a></li>
<li><a href="">Delivery</a></li>
<li><a href="">About us</a></li>
<li><a href="">Terms & Conditions</a></li>
<li><a href="">Returns</a></li>
</ul>
This works, but as the text is centered inside every li element, there is some space on the left and on the right. I am trying to make the text “touch” the edges of the ul element (which takes 100% width of the parent element). So if the ul element has a width of 1240px, I am trying to make the text take up 1240px, from end to end.
This is what it looks like when I did the page mockup in photoshop:
the blue lines are the edges (with one indicating the middle).
When I use the flexbox code I wrote, it appears like this:
Is there a way to make this appear like I originally wanted it?
4
Answers
Remove
flex: 1
from theli
. You do not want the elements to grow as this will prevent the text from reaching the extremities.Add
justify-content: space-between;
to theul
. You are currently centering the elements which will cause them to bunch together.You also need to remove the default
ul
padding, but presumabaly you are doing this already.List elements have indentation to make room for markers.
Remove the default space on the list elements. (Also, a lot of your code isn’t necessary.)
Even better, clean up the HTML, as well. Get rid of the list elements and use the simpler and semantically valuable
nav
element.The CSS in this codesandbox returns what you seem to want (it uses React, but for the CSS : https://codesandbox.io/s/wandering-sound-1cme5
The key points I see :
body
‘s margin to 0. As a general rule, to ensure consistent styling across browsers, you might want to use a normaliser tool like this: https://necolas.github.io/normalize.css/, or a complete reset like this : https://meyerweb.com/eric/tools/css/reset/ to take care of that kind of baseline styles.text-align: center
. They are not needed if you usejustify-content: space-between
justify-content: space-between
on the flex wrapper (ul
)ul
by settingpadding-left: 0
li
are mostly unnecessary, afaik, and onlylist-style: none;
should be needed for your purpose.Keep your flexbox code and use
justify-content: space-between;
, so your items will be like this:Just don’t forget to make sure your flexbox direction is set to “row”.
Just an extra tip: Since you are doing a navigation bar, don’t forget to use the
<nav>
tag for better html semantics and accessibility.http://html5doctor.com/nav-element/