CSS Padding vs. Positioning

Padding and positioning are two properties of CSS (Cascading Style Sheets) that affect the size of any HTML element such as divs, tables or paragraphs. Using these two properties in conjunction with each other sometimes proves tricky because padding adds to the overall dimensions of any element. Use the box model to visualize what these different properties do.

  1. The CSS Box Model

    • The box model defines how browsers calculate the dimensions, padding, margins and borders of every HTML element. Whether or not an element is shaped like as such, you can think of it as a rectangular box. Content, borders and padding go inside the box. Margins go outside the box. The model applies to both inline elements and block-level elements.

    Padding

    • Padding adds space around content inside an HTML element. Consider a div that contains a block of text. When you apply a background to the div without adding padding, the text will touch the edges of the background. Since this is not attractive on a Web page, it makes sense to add some spacing so the background is larger than the text. Padding accomplishes this.

    Positioning

    • In CSS, you can position elements using either the relative or absolute methods. When you add a div to the bottom of your HTML code and give it an absolute position of zero pixels from the top and left of the page, it will float up to the top-left corner of the browser screen. In relative positioning, a position of 0 pixels top and left does nothing, but a position of 20 pixels from the left moves the element 20 pixels to the left of where it would normally display on the screen. Elements with absolute positioning nested inside elements with relative positioning take their coordinates from the containing element.

    Effects of Padding On Positioning

    • Though padding adds space between the edge of the HTML element and its content, it still adds to the width of the element. When you add 20 pixels of padding around all sides of a div given a width of 200 pixels, the new width of the div becomes 240 pixels. Take this into account when positioning elements on the page in CSS. For example, if you use absolute positioning for two divs on the page with the intention of stacking one upon the other, and the top div is 100 pixels tall with 20 pixels of padding all around, then the next div needs to go 140 pixels down on the page.

Related Searches:

References

Comments

Related Ads

Featured