Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to specify margin and padding in CSS?

Are these valid values for margin and padding in CSS?

margin: 0px 10px;
padding: 5px 0px 10px;

I thought that you always had to specify all four sides:

margin: 0px 10px 0px 0px;
padding: 5px 0px 10px 0px;

Also, when I write CSS like margin: 0px 10px 0px 0px; my editor IntelliJ warns me that the px is redundant. Should properties like this be written differently?


For anyone reading this post, the answer lies in all of the responses. Each clarifies the shorthand aspect. Thanks to all who responded.

like image 937
Elijah Avatar asked Nov 28 '22 07:11

Elijah


1 Answers

You can specify fewer than 4 as a 'short-hand', which sets several properties to the same value at the same time; for example, the CSS documentation says:

body { margin: 2em }         /* all margins set to 2em */
body { margin: 1em 2em }     /* top & bottom = 1em, right & left = 2em */
body { margin: 1em 2em 3em } /* top=1em, right=2em, bottom=3em, left=2em */

The dimension (e.g. px) is redundant when (only when) the value is 0.

like image 198
ChrisW Avatar answered Dec 09 '22 17:12

ChrisW