简体   繁体   中英

css margin, padding styles

I know I can declare margin for top then bottom like this;

  margin: 10px 6px;

I know for all the same;

 margin: 10px;

I know for all individual;

 margin: 0 8px 9px 1px;

But on some sites I have seen examples such as;

 margin: 2px 2px 0;

and

 margin: 0 8px 2px;

Anyone care to explain how this works??

The margin and padding are defined in this order:

  • T - top
  • R - Right
  • B - Bottom
  • L - Left

Short-hands:

margin: a;      /*= a a a a*/
margin: a b;    /*= a b a b*/
margin: a b c;  /*= a b c b*/
margin: a b c d;/*= a b c d*/
/*Where a, b, c and d are values. Valid values consists of at least one digit
 * and a unit, e.g.: 12px. 0 (zero) doesn't require a unit */

This is one instance where w3schools is a fine reference .

margin:25px 50px 75px;

  • top margin is 25px
  • right and left margins are 50px
  • bottom margin is 75px

Other reference:

margin: 1px 2px 3px;

是相同的

margin: 1px 2px 3px 2px;

It's probably helpful to first explain this syntax:

margin: 5px 10x;

In your question you mentioned that this allows you to set the top and then bottom margins, but that's not exactly correct. The two-value syntax specifies which values to use for the top and bottom and then the left and right . The code above, for example, specifies 5px margin on the top and bottom and 10px margin on the left and right.

If we add a third value to it:

margin: 5px 10px 15px;

...it will behave the same as the two-value syntax above, but set the bottom margin to 15px . So, to be explicit, the three values here are specifying that the top should be 5px , the left and right should be 10px , and the bottom should be 15px .

The order is top, right, bottom, left. Missing off the last value (for left) would tell the parser to inherit the left value from the right value (2nd value) that's been provided.

In CSS, you can set the shorthand from 1 to 4 ways to satisfy the conditions: here is a short breakdown

4 way

margin:Npx NNpx NNNpx NNNNpx;
top margin = N, right = NN, bottom = NNN, left = NNNN

3 way

margin:Npx NNpx NNNpx;
top margin = N, right and left = NN, bottom = NNN75px

2 way

margin:Npx NNpx;
top and bottom margins = N, right and left = NN

1 way

margin:Npx;
all four margins = N

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM