Chapsterj
Chapsterj

Reputation: 6625

margin left and right on width 100%

I have a div that's set to width 100%. I wanted to set a margin right and left of 20px. For some reason only the left is being pushed over 20px. It ignores the right. Is this because of the 100%?

Upvotes: 3

Views: 6855

Answers (4)

Victor Martinez
Victor Martinez

Reputation: 1112

A div will use all available space , unless you start floating. Remove the width and should be fine.

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

Not stupid at all. What's happening is you are trying to set a banner somewhat like this: (# is the margin)

==========
#--------#
==========

but it ends up like this:

==========
#----------#
==========

making it look like this:

==========
#---------
==========

adding a margin does not reduce the set width of 100%.

you might try using left:20px; right:20px; and leave the width and margin auto

EDIT
or just leaving width off like the others have suggested. :P

Upvotes: 5

Matijs
Matijs

Reputation: 3148

Remove the 100% width and only give it 20px margin left and right and you'll be fine.

Upvotes: 1

gilly3
gilly3

Reputation: 91467

Remove the width. As with all block elements, divs will automatically expand to fill the available width. When you specify a width of 100%, you are telling it to be the same size as its container, not to fill the available width. As width does not include margins, specifying the margin in addition to the width causes the div to be shifted to the right by the left margin amount, and the right margin exists off the screen.

Upvotes: 9

Related Questions