Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

how to set css width equal to length of longest text

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/

?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...