CSS Tutorial

Margins

Understanding Margins

Margins are spaces around elements, such as text or images, that provide breathing room and improve readability. There are four types of margins:

  • Top margin: Space above the element
  • Right margin: Space to the right of the element
  • Bottom margin: Space below the element
  • Left margin: Space to the left of the element

Setting Margins

In CSS, margins can be set using the following properties:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

Practical Example

To give 20 pixels of space around a paragraph of text, use the following CSS:

p {
  margin: 20px;
}

Creating Space and Controlling Positioning

Margins can be used to create space between elements and control their positioning. For example, to create a 10-pixel gap between two paragraphs, use the following CSS:

p + p {
  margin-top: 10px;
}

Improving Accessibility

Ensuring that margins are adequate is essential for accessibility. Sufficient margins improve readability, particularly for users with low vision or dyslexia. Consider the following guidelines:

  • Use consistent margins throughout the site.
  • Avoid using negative margins.
  • Use relative units (such as em or %) instead of absolute units (such as px) to ensure margins are responsive.