Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you prevent expanding outer element when adding padding? [duplicate]

Tags:

css

I'm not a designer. When writing CSS it often happens that I need to add some padding to an element. How do you avoid that padding to propagate to the parent element ?

HTML:

<div id="outer">
  <input id="login">
</div>

CSS:

#outer {
  width: 300px;
}

#login {
  width: 100%;
  padding: 1em;
}

If you use that HTML+CSS, you'll see that the #outer element is bigger than 300px. The easiest solution if to re-write the #login's width to "300px - to_pixel(1em)". It works well but also means that now the font size needs to be fixed. Is there another way where I don't need to convert everything in pixels ?

like image 384
zimbatm Avatar asked Nov 28 '11 09:11

zimbatm


People also ask

How do you prevent padding from increasing width?

To avoid the width or height getting increased or decreased when using CSS properties like margin , padding , etc, we can use the CSS property called box-sizing and set its value to border-box on the element in CSS.

Does padding make an element bigger?

If an element has a specified width, any padding added to that element will add to the total width of the element. This is often an undesirable result, as it requires that an element's width be recalculated each time the padding is adjusted.

Why does padding make div bigger?

Now, because of the way the box sizing works in CSS, adding the padding to your element will add to its dimensions, since the width of the padding area will be added to the width of the content area, and so the total width (and height) of the element will increase.

Does the padding property add space to the inside of the element?

An element's padding area is the space between its content and its border. Note: Padding creates extra space within an element. In contrast, margin creates extra space around an element.


2 Answers

You can css box-sizing property like this:

#outer {
  width: 300px;
    background:red;
    height:100px;
}

#login {
  width: 100%;
  padding: 1em;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    box-sizing:border-box;
}

http://jsfiddle.net/TQXdn/

box-sizing does not work in IE7

like image 66
sandeep Avatar answered Oct 11 '22 21:10

sandeep


What you want is the box-sizing property. Take a look at this jsFiddle for it in practice. Just add this:

-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;

to your #login CSS. This is supported in most modern browsers, including IE8+.

like image 32
CherryFlavourPez Avatar answered Oct 11 '22 20:10

CherryFlavourPez