CSS中margin
和padding
的这些有效值是什么?
margin: 0px 10px;
padding: 5px 0px 10px;
我认为你总是必须指明所有四个方面:
margin: 0px 10px 0px 0px;
padding: 5px 0px 10px 0px;
另外,当我像margin: 0px 10px 0px 0px;
那样编写CSS时,我的编辑IntelliJ警告我px
是多余的。这样的属性应该用不同的方式写出来吗?
答案 0 :(得分:12)
它们都是正确的,它们只是写作的不同方式。
长记:
margin|padding: top right bottom left;
简写符号:
margin|padding: top left&right bottom;
margin|padding: top&bottom left&right;
margin|padding: top&right&bottom&left;
对于第二个问题:如果你写0px
,单位是多余的,因为零是零,无论单位如何,所以你也可以在没有任何单位的情况下写0
。
答案 1 :(得分:10)
您可以指定少于4作为'short-hand',它会同时将多个属性设置为相同的值;例如,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 */
当(仅当)值为px
时,维度(例如0
)是多余的。
答案 2 :(得分:4)
并非必须始终指定所有四个属性。在您的情况下,如果所有其他边距值都已为0,则margin: 0px 10px 0px 0px;
可以更好地写为margin-right: 10px;
。如果值为0,则无需添加px
。
还要看一下速记符号,
margin: 0px; (top, right, bottom, left - 0px)
margin: 2px 4px; (top and bottom - 2px, right and left - 4px)
margin: 2px 4px 6px; (top - 2px, right and left - 4px, bottom - 6px)
答案 3 :(得分:0)
您选择的方式取决于布局。
如果每一方都不同,那么你会以不同的方式做每一方
margin: 10px, 15px, 20px, 25px;
(当然,你可以随时使用它,但这是最好的例子)。
如果顶部和侧面相同,则只需为顶部和底部的第一个数字和侧面的第二个数字。
margin: 10px, 20px;
如果您希望所有4个方具有相同的保证金,那么
margin: 10px;
完成所有4。