I've been polishing up a page I built over the past day or two and have run into an issue after using box-shadow - I was hoping someone might shed some light on an easy way to fix this.
The Setup: I have a div that has a few properties, including width, max-width, and box-shadow.
#mydiv {
width:100%;
max-width:1200px;
-webkit-box-shadow: 0px 0px 20px rgba(0, 0, 0, 1);
-moz-box-shadow: 0px 0px 20px rgba(0, 0, 0, 1);
box-shadow: 0px 0px 20px rgba(0, 0, 0, 1);
}
The Problem: The "box-shadow" property adds 40px to the width of the div element - 20px on each side. When a screen is small enough that the content should hit the 100% width attribute, we see a horizontal scroll-bar. After digging through the CSS I discovered it was because the div was technically something more like width: 100% + 40px;
What I've Tried: I've considered setting overflow:hidden on the parent div, but I do have a min-width set that would then make content inaccessible. I've also tried using a percentage for the size argument in the box-shadow CSS - 1% for example - and then setting the div's width to 98% - but the box-shadow CSS doesn't seem to accept a percentage for its size. I also have considered using javascript to test the browser width and then display or hide the box-shadow element accordingly, b开发者_JS百科ut it doesn't seem like the optimal solution.
There has to be a simpler way to handle this. Thoughts?
It's a browser bug.
The spec used to be unclear about this, but wording has since been added to clarify that shadows shouldn't trigger scrolling:
Shadows do not trigger scrolling or increase the size of the scrollable area.
But as a result of this earlier omission, most browsers did trigger scrolling for shadows. This has now been fixed in all recent browsers.
In older browsers, you'll either have to live with the scrollbars, add overflow-x: hidden
to your #mydiv
and hope it doesn't break anything, or find another way to add shadows (e.g. using good old PNGs).
Also see the following two related questions:
- Firefox & CSS3: using overflow: hidden and box-shadow
- CSS box shadow on container div causes scrollbars
There's a workaround to the problem of scroll bars in fluid width sites with box shadow.
If you add an @media instruction in your CSS you can detect when the browser window is at a certain width (modern browsers support this and IE9 should too).
For example, for a centered pagewrap div with a max-width set to 940px, try adding this to your stylesheet:
@media screen and (min-width: 998px) { div#pagewrap { -moz-box-shadow: 3px 8px 26px #a1a09e; -webkit-box-shadow: 3px 8px 26px #a1a09e; box-shadow: 3px 8px 26px #a1a09e; } }
The min-width of 998px in the @media css is to make the drop shadow disappear just before it triggers the scroll bar.
精彩评论