Yarin
Yarin

Reputation: 183989

Why do negative margins affect my page width?

Please reference the following example:

In it, an outer div 200px wide is meant to establish our page width. It contains an inner div 400px wide, but with left/right negative margins of -100px.

My intended end result is that the browser register total content width at 200px, not 400px, but horizontal scrollbars show up as soon as the window is resized to less than 400px. What is going on here?

Upvotes: 3

Views: 4506

Answers (4)

CVM
CVM

Reputation: 800

Gareth's answer is correct. Even with negative margin, the div is still part of the standard page flow and will not be ignored with respect to layout. Genuine page content cannot be ignored for scrolling purposes.

However, if you're doing this for an aesthetic, such as having a shadow down the sides of the page that extends beyond your max width, this can be achieved with a background - this question should help.

Upvotes: 1

Brent Friar
Brent Friar

Reputation: 10609

as Gareth already mentioned, margins do not affect the box size. The solution is rather simple. The outer container needs to be 400px, this is what is going to trigger the horizontal scroll bars. The inner container needs to be 200px with 100px left and right margins. When you resize the window, the scroll bars appear as soon as you have gotten smaller than the outer container.

http://jsfiddle.net/58VFB/

Upvotes: 1

wdm
wdm

Reputation: 7189

Try adding this to your CSS...

body {
    overflow-y: scroll;
    overflow: -moz-scrollbars-vertical;
}

Upvotes: 0

Gareth
Gareth

Reputation: 5718

Negative margins don't adjust the width of the div. A negative left margin will move the div to the left of it's position in the flow of the page, and a negative right margin will allow other elements to overlap the right hand side of the div by the amount of the margin.

You can hopefully see what I mean in this jsFiddle.

From your question it sounds like you need overflow: hidden to contain a large div within a smaller one without spilling out of its boundaries.

Upvotes: 2

Related Questions