±«Óătv

Margins and padding

The box model

Margins and padding are used to move and push content from the edges of elements. This is a lot like a box.

Margin, border and padding all labeled and wrapped around a box marked "content".

Margin: A transparent area around the outside of an element.

Padding: a transparent area inside the edge of the element.

Margins

We have five different margins that can be used:

  • margin - this adds a margin all around an element
  • margin-left
  • margin-right
  • margin-top
  • margin-bottom

A margin also has properties associated with it:

  • auto (size calculated by the browser)
  • length (stated in pixels (px))

An example of using margins is illustrated below:

An example of a 50px margin around all four sides of a red square. The margin is separate from the square.

Code for margins below:

<html>
<head>
<style>
p.example {
		background-color: red;
		width: 200px;
		height: 200px;
		color: white;
		margin: 50px
		}
</style>
</head>
<body>
<h1>Margins Example</h1>
When we use margins, we can push sections of our webpage around. 
In this case, we can push this red block below by 50px on all sides.
<p class="example">This text should be in a red block that has been 
pushed by the margin property by 50px on top, right, bottom, left.</p>
</body>
</html>

Padding

As with margins, there are five different ways to state padding:

  • padding - this adds padding all round an element
  • padding-top
  • padding-bottom
  • padding-left
  • padding-right

Padding has a length property which is in pixels (px).

We will stick to using our red block from the previous example, this time we will add a padding of 50 pixels to each side of the block.

An example of using padding is illustrated below:

Padding example

When we use padding, we can give our sections of webpages some padding around text and other objects. In this case, the block below has a padding of 50px.

An example of a 50px padding around text inside a red square. The padding is part of the square.

Code for padding below:

<html>
<head>
<style>
p.example {
		background-color: red;
		width: 200px;
		height: 200px;
		color: white;
		padding: 50px
		}
</style>
</head>
<body>
<h1>Padding Example</h1>

When we use padding, we can give our sections of webpages some padding around text and other objects.
In this case, the block below has a padding of 50px.
<p class="example">This text should be in a red block that has been 
given padding around of 50px on <b><u>each</u></b> side of the block.
In effect the block will gain 50px on top, bottom, left and right.</p>
</body>
</html>