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
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 increasingmax-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.Hope this is helpful.
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