skip to Main Content

Just A quick question thou why is it that when you specified a max-width of a specified pixel value and then have a width of 100%, what is effect of having a width of 100% even though their is already max-width with a specified value and even if as the smaller screen decreases the max-width will just take care of it since it will just have an auto right.

For example when you have a container let’s say has width of 500px and then a child element has a max-width of 300px and then width of 100%, what does having width of 100% actually have an effect on the child element ?

3

Answers


  1. max-width and width are 2 different CSS properties and have good use together. If you want to set a fixed width for most of the screen sizes but still you want to set a max limit where you want to stop rendering that fixed width, you can use both of these properties together. For example: Let’s say I have a header which I want to have 100% width for most smaller screens but for much bigger screens, I don’t want to cover the 100% width. Rather, I want to limit it at a specific width and let’s say 1200px. Then I can write the codes below. You will see it will cover 100% of the width for smaller screens but when the viewport width is getting bigger it will stop at 1200px and will not cover the 100% of the screen anymore.

    *{
        margin: 0;
        padding: 0;
    }
    
    header{
        max-width: 1200px;
        width: 100%;
    }
    <header style="background-color: red; height: 100px; margin: 0 auto;"></header>
    Login or Signup to reply.
  2. max-width value will still take precedence.

    Login or Signup to reply.
  3. For example, on this CSS code:

    .content { 
      width: 100%;
      max-width: 1200px; 
      margin: 0 auto; 
    } 
    

    The .content will always try to be as wide as its container (because of width: 100%). But once the container exceeds 1200px, .content won’t grow any further because of the max-width: 1200px. The margin: 0 auto centers .content when the screen width is larger than 1200px.

    Basically, width: 100% ensures the element is flexible on smaller screens, while max-width ensures it remains beautiful and doesn’t stretch too much on larger screens.

    Hope that you are clear with this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search