Reputation: 617
Here is my primary nav code:
<nav id="nav-primary">
<ul>
<span class="nobr">
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Help</a>
</li>
</span>
<span class="nobr">
<li>
<a href="#" class="active">Events</a>
</li>
<li>
<a href="#">Contact</a>
</li>
</span>
</ul>
</nav>
The navigation options appear side-by-side and, when the viewport gets too narrow, the options always break into one line of 3 items and one line of 2 items.
How can I write this in valid HTML? I understand that I should not put the <span>
outside the <li>
s.
Upvotes: 0
Views: 257
Reputation: 60563
You have to use media queries
for that
NOTE: Choose the breakpoints that fits you better
* {
box-sizing: border-box
}
body,
ul {
margin: 0
}
ul {
font-size: 0; /* fix inline-block gap */
padding: 0;
}
li {
list-style: none;
width: 100%; /* 1 column */
display: inline-block;
font-size: 16px; /*reset font-size */
background: lightyellow;
text-align: center;
border: 1px dotted red;
margin:3px 0
}
@media (max-width: 768px) {
li {
width: 50%; /* 2 even columns */
background: lightgreen
}
}
@media (max-width: 468px) {
li {
width:calc( 100% / 3); /* 3 even columns */
background: lightblue
}
}
<nav id="nav-primary">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Help</a>
</li>
<li>
<a href="#" class="active">Events</a>
</li>
<li>
<a href="#">Contact</a>
</li>
</ul>
</nav>
Upvotes: 1
Reputation: 2825
You can handle it using css not html so html will be like this:
<nav id="nav-primary">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Help</a>
</li>
<li>
<a href="#" class="active">Events</a>
</li>
<li>
<a href="#">Contact</a>
</li>
</ul>
</nav>
and in your css you will make float:left to li so they will be side by side and when the viewport gets too narrow here you can use media queries which will give another style to make you nav to be in two lines like this :
li{
float:left;
margin-right:10px;
}
@media only screen and (max-width: 481px) {
li{
width:31.33%;
margin-right:2%;
}
}
in the previous css I gave a width:31.33% to li so it will be only three in first line and two in the second line
Demo : https://jsfiddle.net/IA7medd/g22fgr5k/
Upvotes: 1