父母填充与孩子的保证金 [英] Padding on parent versus margin on child

查看:81
本文介绍了父母填充与孩子的保证金的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想在一个(逻辑)容器div中放置一些(逻辑上有意义的)div时,它们之间有一些空格,



这两种方式中的哪一种更合乎逻辑?


  • 设置容器的填充属性

  • 设置内部div的margin属性



有时,我在容器中包含多个元素,如下所示:





在这种情况下,我需要独立于元素周围的空间来设置元素之间的空间。对于之间的空间,我不能使用容器的填充属性,并且必须使用里边元素的边距(-left或-right)。考虑到这一点,为了设置容器和元素之间的空间,我想知道是否更有意义的设置元素的边距(-left,-right,-top,-bottom)或容器的填充。



我使用flexbox。我也有设置为 box-sizing:border-box; 。如果需要,我可以自由使用CSS选择器,例如 nth-child

p>我宁愿在容器内的 div 上设置边距。



假设黑色 div 下面是包含的外容器:display:flex width:300px height:200px 。当您将 padding:30px padding分配给外部 div 时,这将导致 360px 的宽度和 260px 的高度。鉴于你不会期望容器伸展,这将影响容器div周围的元素。因此,最好对内部 div 使用保证金。 b
$ b


当您在内部 div之间分配保证金和容器,实际的外部 div 不会移动,并且边距只会影响内部div,因此不会影响它周围的元素。

如果你使用 box-sizing:border-box; 那么情况会相应改变,所以它是完全的取决于元素的实际大小。在内部元素上使用margin / padding将是正确的方法。


When I want to place some (logically meaningful) div inside a (logical) container div with some space apart as below,

which of the two ways would be more logically correct?

  • Set the padding property of the container
  • Set the margin property of the div that is inside

Sometimes, I have more than one element in the container like this:

For such cases, I would need to set the space between the elements independently from the space surrounding the elements. For the space between, I cannot use the padding property of the container, and I have to go with the margin (-left or -right) of the elements inside. Taking this into consideration, for setting the space between the container and the elements, I am wondering whether it makes more sense to set the margin (-left, -right, -top, -bottom) of the elements or the padding of the container.

I use flexbox. And I also have the setting as box-sizing: border-box;. I am free to use CSS selectors such nth-child if necessary.

解决方案

I prefer to set margin on the div that resides inside the container.

Suppose the black div below is the outer container with display: flex, width: 300px and height: 200px. When you assign padding: 30px padding to the outer div, this will result in 360px in width and 260px in height. Given that you won't expect the container to stretch, this will affect the elements around the container div. Hence, it is better to use margin on the inner div.

When you assign margin between the inner div and the container, the actual outer div won't move, and the margin will only affect the inner div, thus not affecting the elements around it.

If you are using box-sizing: border-box; then things will change accordingly, so it totally depends on what actual size the elements has to be. Using margin/padding on the inner elements will be the right way.

这篇关于父母填充与孩子的保证金的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆