乱世@小熊 2010-02-03 03:20 采纳率: 25%
浏览 454
已采纳

什么时候在 CSS 中使用 margin vs padding

When writing CSS, is there a particular rule or guideline that should be used in deciding when to use margin and when to use padding?

转载于:https://stackoverflow.com/questions/2189452/when-to-use-margin-vs-padding-in-css

  • 写回答

18条回答 默认 最新

  • 北城已荒凉 2012-02-07 20:59
    关注

    TL;DR: By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.

    To me the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't. Consider two elements one above the other each with padding of 1em. This padding is considered to be part of the element, and is always preserved. So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element. Thus content of the two elements will end up being 2em apart.

    Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap. So in this example you will end up with the content of the first element followed by 1em of combined margin followed by the content of the second element. So the content of the two elements is only 1em apart.

    This can be really useful when you know that you want say 1em of spacing around an element, regardless of what element it is next to.

    The other two big differences is that padding is included in the click region and background color/image, but not the margin.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(17条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据