Home > Software design >  How to set a css property depending on desktop or mobile view?
How to set a css property depending on desktop or mobile view?

Time:07-09

I would like to have 2 different margin for the same div depend on mobile and desktop view.

The code below can perform a margin-left: 70px; on desktop. The problem arises on mobile view, it doesn't reset to margin-left: 0px;

How can I do it ?

Thanks.

.body-container {
  padding-left: 0px;
  padding-right: 0px;
  max-width:1350px;
}
.content {
  margin-left: 70px;
}
.content-collapsed {
  margin-left: 0px;
}

CodePudding user response:

You're not resetting margin in .content

You need to use media queries

The solution below uses non-mobile approach

body {
 margin: 0;
}

.content {
  background: red;
  margin-left: 70px;
}

@media (max-width: 800px) { /*choose the width you prefer*/
  .content {
    margin-left: 0;
  }
}
<div >content</div>

The solution below uses mobile approach (recommended, also is the same used by bootstrap 4)

body {
 margin: 0;
}

.content {
  background: red;
  margin-left: 0;
}

@media (min-width: 800px) { /*choose the width you prefer*/
  .content {
    margin-left: 70px;
  }
}
<div >content</div>

CodePudding user response:

You can use media queries (MDN).

Example :

body {
  margin: 0;
}
div {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin-left: 0px; /* mobile*/
}
/* screen width higher than 750px */
@media screen and (min-width: 750px) {
  div {
    margin-left: 70px; 
  }
}
<div></div>

CodePudding user response:

Use media query. Add:

/* For mobile*/
@media only screen and (max-width: 768px) {
    div {
        margin-left: 0;
    }
}

CodePudding user response:

This is the solution that worked the best for my case:

                  <style>
              .body-container {
        padding-left: 0px;
        padding-right: 0px;
        max-width:1350px;
    }

.content {margin-left: 70px;}

@@media (max-width: 800px) { /*choose the width you prefer*/


.content {
margin-left: 0px;
min-width: 100%;


}}}
  </style>

Thank you. You made my day.

  • Related