i

Learn HTML and CSS in 10 Days

Margins and Padding

Contingent upon the element, the browsers might provide pre-defined paddings and margins to the element to help with clarity and legibility. We will come across this with text-based elements. The pre-defined margins, as well as padding for these elements, might vary with different browsers and elements. In the first chapter, we talked about CSS reset to condition these default values down to zero. Doing so enables us to work starting from the earliest stage and to indicate our very own values.

Margins

The margin property enables the user to set the measure of the space that encompasses an element. Margins are completely transparent, and it falls outside of the border for an element.  Look at one of its examples:

div {

  margin: 20px;

}

Padding

The property of padding is much similar to that of the property of margin; the ‘padding’ property provides the spacing straightforwardly within an element. Check the code:

div {

  padding: 20px;

}

Unlike the margin property, this padding property works vertically on inline-level elements.

Margin and Padding declarations

CSS offers us the ability to provide values to properties in different ways. We can utilize the shorthand process i.e., listing a couple of values with one property. Or we can also go with the longhand property i.e., listing several values and properties one after the other. It is important to note that whatever be the case, one should use the right format for value and properties.

The 'padding,' as well as the 'margin' properties, comes under both the shorthand and the longhand category. While dealing with the shorthand 'margin' property, we define only one value.

div {

  margin: 20px;

}

To provide one value to both top and bottom, and a different value to both right and left side of an element, define the 'margin' property with two values: one for top and bottom and the other for left and right. In the example below, we are keeping the margin of top and bottom as 10 pixels and that of left and right as 20 pixels.

div {

  margin: 10px 20px;

}

If you want to give unique values to all the four sides of the element, then write all the value in the order as top, right, bottom, and left. In the below example, we are giving 10 pixels on top, 20 on the right, 0 on the bottom, and 15 on the left.

div {

  margin: 10px 20px 0 15px;

}

Utilizing the padding and the margin property alone with any number of qualities is known as shorthand. With the help of longhand, we can set the one side value at a time. The property name and the side where the property needs to be applied is connected with a dash. Example – 'padding-right' will acquire only one value and will set the right padding for that element. The same method goes with the margin as well.

div {

  margin-top: 10px;

  padding-left: 6px;

}