Margin property with three values

Question

I tried giving margin three values and it worked, why?

Answer

As we know, the single declaration of margin can take one value and it will apply it to every side of the element; if we give it four different values, each one of them will relate to each side in clockwise order ( top, right, bottom left), and if we give the property two values CSS will account the first one to relate to top and bottom, and the second one to right and left. Yet, using three values works because CSS counts it as if the fourth value was the same as the second, therefore it is read as:

margin: top right/left bottom;

So, if we had this for an element:

margin:50px 20px 1px;

Right and left will have a margin of 20px each, which can be illustrated like this:

05%20PM

31 Likes

can we use center value with margin
e.g
margin: center;

A margin surrounds a box, so it can only have top, bottom, left, and right. The center is what contains the element.

5 Likes

@axelkaban

margin: top right/left bottom;

if so,… how can i write one line when i want margin top/bottom in same size and different right/ left value?

You would have to use the top right bottom left shortcut. There is no special shortcut to add margin in one declaration in this order: top/bottom left right

1 Like

I see! thank you! have a good day and night! :slightly_smiling_face:

1 Like

does this structure top right/left bottom also apply to others properties (like padding)?

Hey @websolver89893 :grinning:

For padding… Yes it applies and works similarly, and it might work also for every property that has the same implementation .

@ruby5461951221

I think they didn’t understand your question, the answer is margin: auto;, this rule will make your element’s left and right margin the same and places your element at the center of it’s container, note that your element should have a width less than the width of the container.