Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set css width equal to length of longest text

Tags:

I have quite a challenging task.

I have this menu here... http://jsfiddle.net/K2Zzh/6/

If you hover over 'treatments', the width for the dropdown menu is set at 150px, which is fine, however, if you hover over 'aftercare', you can see this width is too wide. I have tried min-width, auto, inline-block, but no luck so far.

Rather than creating a separate class for each dropdown, is there a clever way of setting the width to only be as large as the longest text per menu?

The css code i have used for the drop down...

.dropdown ul {   position: absolute;   top: 43px;   z-index: 100;   border-left: 1px solid #f6634c;   border-bottom: 1px solid #f6634c;   border-right: 1px solid #f6634c; } .dropdown ul li a {   background-color: #fff;   width: 150px;   text-align: left; }​ 

Thanks in advance.

My HTML Code...

<ul class="mainNav">   <li><a href="">Home</a></li>   <li class="dropdown">     <a href="">Treatments</a>     <ul>       <li><a href="">Body Treatments</a></li>       <li><a href="">Make Up</a></li>       <li><a href="">Skincare</a></li>       <li><a href="">Hand & Feet Treats</a></li>       <li><a href="">Hair Removal</a></li>       <li><a href="">Alternative Therapies</a></li>       <li><a href="">Eye Enhancements</a></li>     </ul>   </li>   <li><a href="">Gallery</a></li>   <li class="dropdown">     <a href="">Aftercare</a>     <ul>       <li><a href="">Body</a></li>       <li><a href="">Make up</a></li>       <li><a href="">Skin</a></li>       <li><a href="">Hand</a></li>     </ul>   </li>   <li><a href="">Contact</a></li> </ul> 
like image 622
Adam Avatar asked Dec 16 '12 17:12

Adam


People also ask

How do I make div width as content?

Using inline-block property: Use display: inline-block property to set a div size according to its content.

What does width 100% means in CSS?

if you specify width:100%, the element's total width will be 100% of its containing block plus any horizontal margin, padding and border.

How do you write maximum and minimum width?

If you want to include both min and max width for responsiveness in the browser, then you can use the following: @media (min-width: 768px) and (max-width: 992px){...} @media (min-width: 480px) and (max-width: 767px) {...}


1 Answers

first step: remove fixed width from .dropdown ul li a

second step: add the css li li {width:100%;}

third step: add .mainNav li a {white-space:nowrap;}

It's ready: http://jsfiddle.net/K2Zzh/10/

like image 170
Sotiris Avatar answered Sep 21 '22 15:09

Sotiris