I have a navigation dropdown menu within a container. The HTML and CSS code provided is meant to display a language dropdown menu. However, I’m experiencing issues where the container’s width doesn’t adjust according to the length of the longest text inside it. I want to ensure that the container is always at least as wide as the longest text and that the entire text is visible. How can I achieve this with the given code?
* {
padding: 0;
margin: 0;
font-family: monospace;
}
.language {
list-style: none;
background: #22438C;
display: inline-block;
}
.container {
display: inline-block;
position: relative;
}
a {
display: block;
padding: 20px 25px;
color: #FFF;
text-decoration: none;
font-size: 20px;
}
ul.dropdown li {
display: block;
}
ul.dropdown {
width: 100%;
background: #22438C;
position: absolute;
z-index: 999;
display: none;
}
.dropdown a:hover {
background: #112C66;
}
.container:hover ul.dropdown {
display: block;
}
<div class="container">
<ul>
<li>
<a class="language" href="#">EN ▾</a>
<ul class="dropdown">
<li><a href="#">English</a></li>
<li><a href="#">German</a></li>
</ul>
</li>
</ul>
</div>
2
Answers
You can add
width: fit-content;
to ul. dropdown div, but doing so will only extend the length of the links, not the dropdown title. If this matters, I’d say adding a width that’s equal to however long your longest link will be to the main dropdown. For example, if your largest link would be 150px long, adding that width to your language class would ensure everything is the same length!I think if you want it to look appropriate
just add width that is larger from 100%
and also add to the body a
max-width
.