How to change spacing of an element. Margins and Paddings
Note: In this tutorial we are using Firebug. If you don’t know what Firebug is, please first visit the How to Customize Your Theme With Firebug article.
This tutorial will help you to better understand the padding and margin CSS properties. These properties are used to arrange the spacing between different elements in the theme.
Margin
Each 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 element). Margins in CSS make up the vertical and horizontal areas between elements. Some elements have margins by default, so often even if you haven’t added a margin, you may still see one.
Margins can be set using the margin
property (which is shorthand, representing the four margin values for an element) or by the longhand margin-top
, margin-right
, margin-bottom
, and margin-left
properties. The order in shorthand is: top, right, bottom, left.
You can define the element margin values the following way:
- margin-top:10px;
- margin-bottom:10px;
- margin-right:5px;
- margin-left:5px;
You can also use the shorthand property:
- margin:15px 10px 12px 7px;
- top margin is 15px
- right margin is 10px
- bottom margin is 12px
- left margin is 7px
.menu{ margin: 0 auto; }
You can learn more about the margin CSS property here.
Padding
The 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 on the element and the content of (inside) the element. The padding is affected by the background color of the element.
You can define the padding value in the following way:
- padding-top: 5px;
- padding-right: 7px;
- padding-bottom: 5px;
- padding-left: 12px;
You can also use the shortand property:
- padding:5px 7px 5px 12px;
- top padding is 5px
- right padding is 7px
- bottom padding is 5px
- left padding is 12px
Note: the padding value is added to the element width and is affected by the element’s background.
In other words we have the element div with class box:
.box{ width:150px; padding: 25px;}
The browser will add the left and right padding values to the box width. As a result you’ll see the box that will be of 200px width.
You can learn more about the margin CSS property here.