I may not be very clear in explaining what I want so be patient with me please.
I’m working on a responsive menu. I would like the list to be centered within its’ div container when the width of the viewport is greater than 480 pixels as soon as the page loads. I can get javascript/jquery to do this when I resize the page but when the page is initially loaded.
HTML
<section id="nav">
<div id="menuToggle">☰</div>
<ul class="menu">
<li><a href="http://google.com/">Home</a></li>
<li>
<a href="#">Products</a>
<ul>
<li><a href="http://google.com/">Computers</a></li>
<li><a href="http://google.com/">Phones</a></li>
<li><a href="http://google.com/">Tablets</a></li>
<li><a href="http://google.com/">Beepers</a></li>
</ul>
</li>
<li><a href="http://google.com/">About</a></li>
<li>
<a href="#">Contact</a>
<ul>
<li><a href="http://google.com/">Advertise</a></li>
<li><a href="http://google.com/">Affiliate</a></li>
</ul>
</li>
<li><a href="http://google.com/">Design</a></li>
</ul>
</section>
CSS
#menuToggle{
display: none;
}
#nav{
position: relative;
top: 0;
left: 0;
z-index: 1000;
width: 100%;
height: auto;
margin: 0;
padding: 0;
background: #000;
}
ul.menu{
width: 100%;
height: 30px;
background: #333;
}
ul.menu > li{
position: relative;
float: left;
}
ul.menu ul{
display: none;
position: absolute;
left: 0;
top: 100%;
margin: 0;
padding: 0 0 0 15px;
background: #ccc;
}
ul.menu a{
cursor: pointer;
display: block;
padding: 0 10px;
line-height: 30px;
color: white;
}
ul.menu li{
list-style: none;
}
ul.menu li:hover{
background: #555;
}
ul.menu li:hover ul{
display: block;
}
#test{
width: 100%;
height: auto;
margin: 0;
padding: 0;
}
#test h1{
color: black;
}
@media all and (max-width: 480px) {
#nav{
}
#menuToggle{
display: block;
font-size: 35px;
color: #fff;
cursor: pointer;
}
#nav{
height: 40px;
}
ul.menu{
display: none;
width: 100%;
height: auto;
margin: 0 auto;
padding: 0;
}
ul.menu > li{
float: none;
width: 100%;
}
ul.menu a{
line-height: 40px;
}
ul.menu ul{
position: relative;
}
ul.menu li{
background: #555;
}
ul.menu li ul{
display: block;
}
}
@media all and (min-width: 481px){
ul.menu li:hover{
background: #555;
}
ul.menu li:hover ul{
display: block;
}
}
javascript/jQuery
$(document).ready(function(){
myFunction();
function myFunction(){
$(window).resize(function(){
if($(window).width() > 480){
$("ul.menu").removeAttr("style");
var $liW = 0;
var $li = $('ul.menu li').each(function(){
$liW += $(this).width();
$('#mw').html($liW);
$('ul.menu').css({
'background' : 'red',
'margin' : '0px auto',
'width' : $liW + "px"
});
});
} else if($(window).width() < 481){
$('ul.menu').css('width', "100%");
}
});
}
$('#menuToggle').click(function(e){
e.preventDefault();
$('ul.menu').toggle();
});
});
EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.