- Part 1: Introducing Selectors
- Part 2: Nesting Selectors
- Part 3: Backgrounds and Colors
- Part 4: Margins, Borders, and Padding
- Part 5: Positioning
- Part 6: Working with Fonts
Cascading StyleSheets (CSS) is a web technology designed for use with HTML. Using CSS allows for the separation of the presentation from the content and can help with customizing layout, colors, and accessibility settings.
Margins, Borders, and Padding
CSS is more than using backgrounds and colors. Rules can also be used to position elements in relation to their parents and the document. There are sets of rules for creating margins, borders, and padding that can help to give more or less visual spacing between elements.
CSS rules follow what is known as the box model. Elements are drawn on the screen in rectangle boxes with different rules affecting how parts of the content are shown and how its own visual spacing affects other elements around it. The box model starts with the margins, the farthest away from the content, and moves “closer” with borders, and padding before getting to the width and height of the element itself.
Similar to how the background rule was a shorthand for other rules using its name, margin is a shorthand for setting the margins (space around) elements on top, right, bottom, and left of the element. When used with a value, it will set the same margins on all sides.
Setting a small margin of, for example, 1 px (pixel) with a selector on the P tag will reduce the space around paragraph elements.
Because it serves as a shorthand for other rules, the different sides (top, right, bottom, left) can also be set as a series of values separated by a single space.
The border rule acts like the margin in that it is a shorthand for other rules (top, right, bottom, left), but it also understands some additional possible values.
Unlike the margin rule, border is also a shorthand for border-style that defines how the border should appear. Possible values for border-style are dotted, dashed, solid, double, groove, ridge, inset, outset, none, and hidden.
The second value in order is the color. As covered in the Backgrounds and Colors section, colors can be represented in many different ways.
Finally, as the last value, the border rule also understands the thickness of the border. This can be expressed in any valid CSS units like “px” for pixels.
The padding rule, like margin and border, is a shorthand for the same different sides (top, right, bottom, and left). Setting a single value will change the padding amount on all sides of the elements.
Like the other rules affected by the box model, the padding rules are affected by the width and height of an element. Changing these affects the visual layout of a HTML document and the elements it affects.
See the Pen Learning CSS: Part 4: Margins, Borders, and Padding by Dan Cox (@videlais) on CodePen.