Reputation: 3653
I got this HTML code:
<div class="tab">
<a href="#">SPECS</a>
<div class="sub-menu">
<a href="#">Specs 1</a>
<a href="#">Specs 2</a>
<a href="#">Specs 3</a>
</div>
</div>
<div class="tab">
<a href="#">GALLERY</a>
<div class="sub-menu">
<a href="#">Gallery 1</a>
<a href="#">Gallery 2</a>
<a href="#">Gallery 3</a>
</div>
</div>
What I'm trying to do, is that I don't want to specify the width of the .sub-menu in CSS, I want it to be dynamic, varying from the content of the div. I tried doing this with jQuery:
var width = $(".sub-menu").width();
$(".sub-menu").css("width", width);
But it's not working, it's giving the all the .sub-menu divs a width of 0px. I want maybe to use the .each function, so every .sub-menu would get its width and apply as css. I hope I was clear enough.
Thanks.
Upvotes: 0
Views: 937
Reputation: 5610
$(function() {
var smWidth = $(".sub-menu").width();
$(".sub-menu").css({ width: smWidth + 'px' });
});
Upvotes: 0
Reputation: 6124
<script>
jQuery(document).ready(function(){
$( ".sub-menu" ).each(function( index ) {
width=$(this).width();
$(this).css('width',width+'px');
});
});
</script>
Upvotes: 0
Reputation: 8715
The thing is that width()
returns a number. But the CSS rule requires Npx
. Use this:
var width = $(".sub-menu").width() + "px";
$(".sub-menu").css("width", width);
Upvotes: 1
Reputation: 324640
Add this to your CSS:
.sub-menu {display:inline-block}
This will make the menu take the width required by its content, no more.
Upvotes: 1