Margin & Padding Declarations
In CSS, there is more than one way to declare values for certain properties. We can use longhand, listing multiple properties and values one after the other, in which each value has its own property. Or we can use shorthand, listing multiple values with one property. Not all properties have a shorthand alternative, so we must make sure we are using the correct property and value structure.
The
margin
and padding
properties come in both longhand and shorthand form. When using the shorthand margin
property to set the same value for all four sides of an element, we specify one value:1 2 3 4 | div { margin: 20px; } |
To set one value for the
top
and bottom
and another value for the left
and right
sides of an element, specify two values: top
and bottom
first, then left
and right
. Here we are placing margins of 10
pixels on the top
and bottom
of a <div>
and margins of 20
pixels on the left
and right
:1 2 3 4 | div { margin: 10px 20px; } |
To set unique values for all four sides of an element, specify those values in the order of
top
, right
, bottom
, and left
, moving clockwise. Here we are placing margins of10
pixels on the top
of a <div>
, 20
pixels on the right
, 0
pixels on the bottom
, and15
pixels on the left
.1 2 3 4 | div { margin: 10px 20px 0 15px; } |
Using the
margin
or padding
property alone, with any number of values, is considered shorthand. With longhand, we can set the value for one side at a time using unique properties. Each property name (in this case margin or padding) is followed by a dash and the side of the box to which the value is to be applied: top
, right
, bottom
, orleft
. For example, the padding-left
property accepts only one value and will set theleft
padding for that element; the margin-top
property accepts only one value and will set the top
margin for that element.1 2 3 4 5 | div { margin-top: 10px; padding-left: 6px; } |
When we wish to identify only one
margin
or padding
value, it is best to use the longhand properties. Doing so keeps our code explicit and helps us to avoid any confusion down the road. For example, did we really want to set the top
, right
, andleft
sides of the element to have margins of 0
pixels, or did we really only want to set the bottom
margin to 10
pixels? Using longhand properties and values here helps to make our intentions clear. When dealing with three or more values, though, shorthand is incredibly helpful.
No comments:
Post a Comment