I have a drop down menu using CSS only. I want the drop down to have automatic width but it takes on the width of its parent (as expected).
What is the best method to get it to have automatic width? (i.e ignore its parents width) without defining a set width.
Here it is on jsfiddle
nav{ background: #000 ; clear: both ; height: 40px ; padding: 0 10px ; }
nav ul{ list-style: none ; }
nav li{ float: left ; position: relative ; }
nav a{ display: block ; float: left ; color: #fff ; text-decoration: none ; padding-right: 30px ; font-size: 120% ; line-height: 40px ; }
nav div{ display: none ; position: absolute ; background: red ; left: 0 ; top: 40px ; }
nav li:hover div{display: block ; }
<nav>
<ul>
<li><a href="#">Home</a>
<div>
<p>example of width not working</p>
</div>
</li>
<li><a href="#">next</a>
<div>example</div>
</li>
<li><a href="#">again</a>
<div>example</div>
</li>
</ul>
</nav>
If it’s not possible with CSS, a Javascript/Jquery solution would suffice.
Try using
white-space: nowrap;on the element that shouldn’t go to the next line.It will keep all the words on the same line and not break into a new line so that it takes automatic width.
In your jsfiddle: http://jsfiddle.net/8BV2N/4/
Also; it is considered best practise to use another ul for your submenu instead of a div. this way search engines can understand the structure of your website better.