NullReference
NullReference

Reputation: 4484

How to add margin without pushing content off screen?

I've got a two column layout that I'd like to add some padding\margin to the right column without pushing the content off screen. In my illustration the arrow points to where I'd like the extra space to be. When I add margin or padding to the red div it pushes the red div off the screen to the right, I'd like to avoid that. Is there a reccomended way to do this? Maybe a wrapper div or something? Thanks

enter image description here

Upvotes: 5

Views: 10431

Answers (4)

James Shuttler
James Shuttler

Reputation: 1374

In order to resolve the issue, as others have pointed out, you need to subtract the value of your padding from the width of the elements, due to the box model. Padding is factored into the calculation which determines element sizing within user agents.

CSS3 adds the box-sizing attribute, which allows you to circumvent the default box model rendering and instead instruct it to include the padding within the element, fully honouring the specified width and height:

/*Property without vendor prefixes*/
box-sizing:border-box;

See this article: http://www.css3.info/preview/box-sizing/

Or, from the spec itself:

border-box The specified width and height (and respective min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height. The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified ‘width’ and ‘height’ properties. As the content width and height cannot be negative ([CSS21], section 10.2), this computation is floored at 0.

Upvotes: 6

Dave
Dave

Reputation: 1175

Is this the sort of thing your after?

jsfiddle

The white space between the left and right div can be altered with the 'margin-left' in the right div's class (more margin giving more white space).

Upvotes: 1

Jason Gennaro
Jason Gennaro

Reputation: 34855

Without seeing the code, all I can tell you is...

If you don't want the content pushed off the screen, then the width of all of your elements -- including margin and padding -- must add up to no more than 100% or the max pixel width you want. (And frequently, when mixing pixels and percentages, you probably want even less.)

Here is a simple example:

<div id="left"></div>

<div id="right"></div>

#left{
    border:1px solid red;
    width:20%;
    height:50px;
    margin-right:4%;
    float:left;
}

#right{
    border:1px solid red;
    width:75%;
    height:50px;
    float:left;
}

http://jsfiddle.net/nWEnj/

Upvotes: 5

The Alpha
The Alpha

Reputation: 146191

If your div is with width of 100px and you add padding-right:20px then it's width will be 120px, so minus the padding amount from your width when you use padding-left/right.

Upvotes: 3

Related Questions