Prolo321
Prolo321

Reputation: 35

How to "automise" width adaptation of div to screensize?

I basically want my webpage to be deliverable on almost any mobile device, very small screensizes included.

This already works, I'm using mediaqueries in CSS to implement different styles for displays of varying size.

However, the way I'm doing it right now feels a bit "unelegant". See this code for example:

@media only screen and (max-width: 550px) {
  .pageStyleEdition{
       text-align: left;
       margin-left:0%;
       margin-right:0%;
       width: 80%;
  }
  .displayFlexStyle{
    display: flex;
    flex-direction: column;
  }
}
 @media only screen and (max-width: 290px) {
   .pageStyleEdition{
      text-align: left;
      margin-left:0%;
      margin-right:0%;
      max-width: 60%;
    } 
   .displayFlexStyle{
       display: flex;
       flex-direction: column;
   }
 }

There's a lot of redundance here, since I'm basically just rewriting the css class over and over with different width-values for the respective screensize, and I would really like to avoid this. Is there any easy way to just say "if the screensize is less than X, dynamically shrink the width so that it still fits into the screen!"?

Upvotes: 1

Views: 41

Answers (1)

Terry
Terry

Reputation: 66093

Remember the cascading component of CSS: when you have styles that apply to a screen of max-width 550px, for example, it is also applicable to screens with a max-width of 290px. In that sense, your second selector can be made way simpler:

@media only screen and (max-width: 550px) {
  .pageStyleEdition{
       text-align: left;
       margin-left:0%;
       margin-right:0%;
       width: 80%;
  }
  .displayFlexStyle{
    display: flex;
    flex-direction: column;
  }
}
 @media only screen and (max-width: 290px) {
   .pageStyleEdition{
      max-width: 60%;
    }
 }

Upvotes: 1

Related Questions