skip to Main Content

Following is my code

body {
    margin: 0;
    border: 2px solid blue;
}


div {
    background-color: rgba(0,0,0, 0.1);
    width: 950px;
    margin:  0 auto;
    padding: 3em;
}


@media screen and (max-width: 950px) {
    div {
        width: auto;
    }

}
<div></div>

I want to see how media query is working. So, if I reduce the viewport width, at one point, horizontal scroll bar appears and further reducing the viewport width, that bar disappears. So, when the horizontal scroll bar appears, we can see that div overflowing the body border. I have set margin: 0 on the body element. So, what is happening ?

2

Answers


  1. Chosen as BEST ANSWER

    After inspecting the page and checking dev tools, I figured out that problem was with the box model. After I put a universal border-box and increasing max-width in media query slightly above the given width of the div, I could get rid of the horizontal scroll bar as I reduce the viewport width.

    * {
        box-sizing: border-box;
      } 
    
    
    body {
        margin: 0;
        border: 2px solid blue;
        
    }
    
    
    div {
        background-color: rgba(0,0,0, 0.1);
        width: 950px;
        margin:  0 auto;
        padding: 3em 0 3em 0;
        border: 2px solid red;
    }
    
    
    @media screen and (max-width: 952px) {
        div {
            width: auto;
        }
    
    }
    <div></div>

    Hope this is helpful.


  2. Initially, the div has a fixed width of 950px and is centered using margin: 0 auto; When the viewport width goes below 950px, the div’s fixed width still remains at 950px. As a result, the viewport can no longer contain the entire div without horizontal scrolling. The browser adds a horizontal scroll bar to allow users to scroll and see the overflowing part of the div.

    The media query (@media screen and (max-width: 950px)) kicks in when the viewport width is 950px or less. It changes the div’s width to auto, which makes the div adapt to the width of the viewport. When the viewport width is just below 950px (but before the media query activates), the div overflows because it is still 950px wide. This causes the horizontal scroll bar to appear, and since the div is centered using margin: 0 auto;, It appears to overflow the body border.

    If you want to prevent the div from overflowing and triggering a horizontal scroll bar when the viewport width is less than 950px, you can add a max-width property to the div to ensure it doesn’t exceed the viewport width

    div {
        background-color: rgba(0,0,0, 0.1);
        width: 950px;
        max-width: 100%;
        margin:  0 auto;
        padding: 3em;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search