Home > Net >  Show different contents based on width of the screen
Show different contents based on width of the screen

Time:01-03

For one element, I have two different texts based on the width of the screen. When the screen width is less or equal than 400px, I want to show narrow. When the screen width is greater than 400px, I want to show large.

Here is the code: https://jsbin.com/qagetoseva/edit?html,css,output

But the problem is that when the width is 400px, this code shows nothing, does anyone know how to amend that?

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <style>
        .me {
          height: 100vh;
        }
    </style>
</head>
<body>
  <div >narrow</div>
  <div >large</div>
</body>
</html>
@media screen and (min-width: 400px) {
    .hide-if-large {
        display:none
    }    
}

@media screen and (max-width: 400px) {
    .hide-if-narrow {
        display: none;
    }
}

CodePudding user response:

Dear friend you have a problem with your css media query.

@media screen and (max-width: 400px) {
.hide-if-large {
    display:none
}    

}

@media screen and (max-width: 1024px) {
    .hide-if-narrow {
        display: none;
    }
}

I changed the second media query for 1024px for fit in tablet sizes. You should create a new media query for larger screens like min-width 1025px

CodePudding user response:

You are using min-width and max-width media queries for same pixel size, which will confuse css. Instead for width <=400 you can use following media query:

@media screen and (max-width: 400px) {
.hide-if-large {
    display:none
} 

And for devices with width >400 you can use this:

@media screen and (min-width: 401px) {
    .hide-if-narrow {
        display: none;
    }
}

In second media query you can use any value greater than 400. For eg 420,500 etc.

  • Related