Skip to content Skip to sidebar Skip to footer

CSS/JS/Jquery - Flex Items For Responsive Screen Sizes

I have a site with 3 items in my navigation which I want to remain on one line. The first is the main menu which has the main site links and should be to the left of the nav bar.

Solution 1:

If you don't want to use media query's you could use Javascript/jQuery but I think you are better off with media queries for this.

However this is a jQuery solution if you prefer that:

Put a event handler on the window load and resize events that check if the window with is equal or the same to 500. If that condition is true then hide the #header_numbers element, if it false show it.

$(window).on('load resize', function(){
  if($(window).width() <= 500) {
    $('#header_numbers').hide();
  }
  else {
    $('#header_numbers').show();
  }
  
  /* Alternative notation use what you prefer
  $(window).width() <= 500 ? $('#header_numbers').hide() : $('#header_numbers').show();
  */
});
#nav{
  height:50px;
  width:100%;
  position:relative;
  display:flex; 
}
ul{
  display:inline-block;
  height:50px;
  line-height:50px;
  list-style:none;
}
li{
  display:inline-block;
}
#main_menu{
  flex:3;
  text-align:left;
}
#header_numbers{
  flex:4;
  text-align:center;
}
#auth_menu{
  flex:3;
  text-align:right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav">
<ul id="main_menu">
  <li>menu item 1</li>
  <li>menu item 2</li>
  <li>menu item 3</li>
</ul>
<ul id="header_numbers">
  <li>menu item 1</li>
  <li>menu item 2</li>
</ul>
<ul id="auth_menu">
  <li>menu item 1</li>
  <li>menu item 2</li>
  <li>menu item 3</li>
</ul>
</div>

Solution 2:

You have to set the display property to none anyways, otherwise, it is not possible without media query to hide anything on different screen size (In your case to smaller screen size).

You can use : -

@media only screen and  (max-width: 540px) {
  #header_numbers{
    display: none;
  }
}

Solution 3:

You are describing the functionality of CSS Media Queries, but say that you don't want to use them :)

You could always use JS, but it is less performat than Media queries

const maxWidth = 500;

document.addEventListener("DOMContentLoaded", () => {
    checkWidth();
});

window.addEventListener('resize', () => {
    checkWidth();
});

function checkWidth() {
    if(window.innerWidth < maxWidth) {
         // ...do somthing with the element
    }
}

Solution 4:

As I know media-query is only way to apply style according screen size in css...

For Example #header_numbers will hide when the browser window is 600px wide or less:

@media only screen and (max-width: 600px) {
    #header_numbers{
        display: none;
    }
}

Post a Comment for "CSS/JS/Jquery - Flex Items For Responsive Screen Sizes"