To adjust styles based on the size of the viewport or screen, you can utilize CSS media queries. This allows for different styling depending on the dimensions of the viewport:
@media (max-width:600px) {
/* hide the div if viewport is 600px or less */
div { display:none; }
}
If your HTML structure looks like this:
<nav>
<span>NAV</span>
<ul>
<li>Home</li>
<li>About</li>
<li>News</li>
</ul>
</nav>
The corresponding CSS would be:
ul {
display:block;
}
li {
display:inline-block;
height:30px;
line-height:30px;
}
span {
display:none;
height:30px;
line-height:30px;
cursor:pointer;
}
@media (max-width:600px) {
ul {
display:none;
}
li {
display:block;
}
span {
display:inline;
}
}
To toggle the dropdown menu when clicking on NAV:
$('span').click(function () {
$(this).siblings('ul').slideToggle('slow');
});
For a live example, refer to this jsfiddle.
If after hiding the dropdown by resizing the viewport width above 600, the menu list doesn't show inline, it could be due to jQuery's inline styling overriding CSS. One way to handle this is to manage viewport resize using jQuery as well. Instead of relying solely on CSS media queries which may not always provide accurate window width values across browsers:
function viewportWidth() {
var e = window,
a = 'inner';
if (!('innerWidth' in window)) {
a = 'client';
e = document.documentElement || document.body;
}
return e[a + 'Width'];
}
Then implement it within the window resize event:
$(window).resize(function () {
if (viewportWidth() <= 600) {
$('span').show();
$('ul').hide();
} else {
$('ul').show();
$('span').hide();
}
});
See the updated jsfiddle for reference.