cmp cmp - 6 days ago 6
CSS Question

How can I use Javascript to detect the width of an area and apply correct menu spacing

Can I use Javascript to detect the size of

menuArea
and then apply each
<li>
the right size to fit the total
menuArea
?



// something like this...

var menuSpace = Math.floor((menuAreaWidth - menuButtonsTotalWidth) / (menuButtons.length - 1));
// set positions
var menuButtonsLeft = 0;

$('#menuArea .menuButtonHolder').each(function(i, buttonHolder) {
if (i < (menuButtons.length - 1)) {
$(buttonHolder).css({
'left': menuButtonsLeft + 'px',
'width': menuButtons[i].buttonWidth + 'px'
});
}

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
#menuArea {
max-width: 1050px;
margin: 0px auto;
}
li {
float: left;
}
li .menuButtonHolder {
display: inline-block;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menuArea">
<ul>
<li><a href="/">Home</a></li>
<li><a href="news.aspx">News and Events</a></li>
<li><a href="social.aspx">Social</a></li>
<li><a href="blog.aspx">Our Blog</a></li>
<li><a href="contact.aspx">Contact</a></li>
<ul>
</div>





Without it, in order for the menu to fill the entire
menuArea
I find myself having to trial and error different
padding: 0px 20px 0px 20px
etc until they all stretch here or there the entire distance across.

Answer

Don't use JavaScript for stuff you can have your CSS do please.

Flexbox has a great way of solving this for you, add these lines to your example:

ul {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

And this if you wish for your elements to respect the same width as the largest element:

li {
    flex: 1;
}

Example snippet:

ul {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

#menuArea {
    max-width: 1050px;
    margin: 0px auto;
}

li .menuButtonHolder {
    display: inline-block;
}

li {
	flex: 1;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}
<div id="menuArea">
<ul>
 <li><a href="/">Home with a really long name.</a></li>
 <li><a href="about.aspx">Home</a></li>
 <li><a href="news.aspx">News</a></li>
 <li><a href="social.aspx">Social</a></li>    
 <li><a href="blog.aspx">Blog</a></li>
 <li><a href="contact.aspx">Contact</a></li>
<ul>
</div>

Comments