Jump to content

Max-width on div with padding problem


eiranix

Recommended Posts

Maybe I'm missing something obvious here, but I'm having a problem with max-width when applied to a div with padding. Can anyone tell me what the issue is here?

 

If I have a div that has a max-width of 960px and a width on 100% it works as expected. If I then add padding, the div does not contract with the browser until it has overlapped it a certain ammount.

<!DOCTYPE html><html><head><style> .content {width:100%;max-width:920px;padding:20px;background-color:white;height:500px;margin-left: auto;margin-right:auto;}body {margin:0px;padding:0px;background-color:red;}</style></head><body><div class="content">But I must explain to you how all this mistaken idea of denouncing of a pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?</div></body></html>
Edited by eiranix
Link to comment
Share on other sites

Remove the width 100% line, you don't need it.

 

Padding, margins and borders are added onto the width, so 100% width + 20px padding will always go outside the window. Block elements automatically take the full width of their container when you don't set their width, and they also take margin, padding and borders into account, so just remove the width.

Link to comment
Share on other sites

.content {  -webkit-box-sizing: border-box;  -moz-box-sizing: border-box;  box-sizing: border-box;}

That fixes it.

 

As Ingolme said, padding adds to the dimensions of the element. A div with 100px width and 20px padding will result in an actual width of 120px.

 

Chris Coyier has a great article on this, as well as Paul Irish.

 

This might not work out for every situation, though, as only IE 8+ supports it (naturally Firefox, Chrome, Opera and Safari have good support).

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...