I have a dynamic menu with a few items. I wanted the items to share the space available such that the bigger text takes more space. And all of them will have equal padding so that the hover color will fill the space defined for it.
-----------------------------------------------------------
| Test | Test Very Bigger Item | Test Bigger item |
-----------------------------------------------------------
The menu will look similar to above without the border. On hover, the background color will need to fill up the space around it.
ul {
width: 600px;
display: flex;
justify-content: space-around;
border: 1px solid blue;
list-style: none;
padding: 0px;
}
li {
border: 1px solid blue;
}
<ul>
<li>
Test
</li>
<li>
Test Very Very Large Bigger Item
</li>
<li>
Test Bigger item
</li>
</ul>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The above code ensures correct spacing but the hover does not take up the space available.
CodePudding user response:
Use this style (everything is dynamic here) -
CSS (modified) -
ul {
width: 600px;
display: flex;
list-style: none;
padding: 0px;
border: solid 1px blue;
}
li {
flex: auto;
text-align: center;
padding: 8px 0;
}
li:hover {
background: blue;
color: white;
cursor: pointer;
}
HTML (no change) -
<ul>
<li>
Test
</li>
<li>
Test Very Very Large Bigger Item
</li>
<li>
Test Bigger item
</li>
</ul>
Working demo here
CodePudding user response:
Alright, according to your comment the width of the ul
must not necessarily be 600px. I'd suggest setting a max-width: 600px
and just give the li
elements an extra padding.
ul {
max-width: 600px;
display: flex;
border: 1px solid blue;
list-style: none;
padding: 0px;
}
li {
padding: 0 2em;
border: 1px solid blue;
min-width: max-content;
}
li:hover {
background: red;
}
<ul>
<li>
Test
</li>
<li>
Test Very Very Large Bigger Item
</li>
<li>
Test Bigger item
</li>
</ul>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Depending on the location of the ul
you can set the elements inside the flex container either to justify-content: flex-start
(if the ul
is placed on the left side of the screen) or justify-content: flex-end
(if the ul
is placed right).
CodePudding user response:
I do some changes:
ul {
width: 600px;
height: 30px;
display: flex;
justify-content: space-between;
align-items: center;
border-top: 1px dashed blue;
border-bottom: 1px dashed blue;
list-style: none;
padding: 0px;
}
li {
border-left: 1px solid blue;
border-right: 1px solid blue;
padding: 0 10px;
height: 100%;
display: flex;
align-items: center;
}
li:hover {
background: red;
}
<ul>
<li>
Test
</li>
<li>
Test Very Very Large Bigger Item
</li>
<li>
Test Bigger item
</li>
</ul>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>