Saturday, 2 August 2014

Margin and padding

Set the margin in an element

An element has four sides: right, left, top and bottom. The margin is the distance from each side to the neighboring element (or the borders of the document).
As the first example, we will look at how you define margins for the document itself i.e. for the element <body>. The illustration below shows how we want the margins in our pages to be.
Examples of margins
The CSS code for this would look as follow:
 
 body {
  margin-top: 100px;
  margin-right: 40px;
  margin-bottom: 10px;
  margin-left: 70px;
 }
 
 
Or you could choose a more elegant compilation:
 
 body {
  margin: 100px 40px 10px 70px;
 }
 
 
You can set the margins in the same way on almost every element. For example, we can choose to define margins for all of our text paragraphs marked with <p>:
 
 body {
  margin: 100px 40px 10px 70px;
 }

 p {
  margin: 5px 50px 5px 50px;
 }
 
 

Set padding in an element

Padding can also be understood as "filling". This makes sense as padding does not affect the distance of the element to other elements but only defines the inner distance between the border and the content of the element.
The usage of padding can be illustrated by looking at a simple example where all headlines have background colors:
 
 h1 {
  background: yellow;
 }

 h2 {
  background: orange;
 }
 
 
By defining padding for the headlines, you change how much filling there will be around the text in each headline:
 
 h1 {
  background: yellow;
  padding: 20px 20px 20px 80px;
 }

 h2 {
  background: orange;
  padding-left:120px;
 }
 
 

Related Posts:

  • CSS Text Property Formatting and adding style to text is a key issue for any web designer. In this lesson you will be introduced to the amazing opportunities CSS give… Read More
  • Margin and padding Set the margin in an element An element has four sides: right, left, top and bottom. The margin is the distance from each side to the nei… Read More
  • The Box Model The box model in CSS describes the boxes which are being generated for HTML-elements. The box model also contains detailed options regarding adjusti… Read More
  • CSS Borders Borders can be used for many things, for example as a decorative element or to underline a separation of two things. CSS gives you endless options w… Read More
  • CSS Links & Pseudo Classes What is a pseudo-class? A pseudo-class allows you to take into account different conditions or events when defining a property for an HTML tag. Le… Read More