CSS 多个带边距的分组元素
采取这个 HTML:
<div>
<div class="block">Hello</div>
<div class="block">Hello</div>
<div class="block">Hello</div>
<div class="block">Hello</div>
</div>
使用配套的 CSS:
div.block
{
float: left;
width: 100px;
height: 100px;
margin: 1px;
background: red;
}
结果是四个块,它们之间有 2 像素 的空间(距左块的右边缘 1 像素,距左块的左边缘 1 像素)右块)。
有没有一种方法可以达到与边框折叠类似的效果? IE。我希望相邻块之间只有一个像素的边距。
这是我经常遇到的更复杂情况的基本示例,我不想通过类似于仅将 margin-left
设置为 1 像素等方式来解决它。
Take this HTML:
<div>
<div class="block">Hello</div>
<div class="block">Hello</div>
<div class="block">Hello</div>
<div class="block">Hello</div>
</div>
With the companion CSS:
div.block
{
float: left;
width: 100px;
height: 100px;
margin: 1px;
background: red;
}
The result of this is four blocks, which have between them 2 pixels of space (1px from the right margin of the left block and 1px from the left margin of the right block).
Is there a way that I can achieve a similar effect to border-collapse? ie. I want there to be only one pixel of margin between adjacent blocks.
This is a basic example of often more complex situations that I run into, and I don't want to get around it by by anything similar to only setting margin-left
to 1 pixel etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有多种方法,其中
一种是
另一种,
您可以查看两种方式的演示此处
There are multiple ways to this
One of them is
Another is
You can check the demo of both way here
如何使用 CSS 选择器
:first-child
和:last -child
更改第一个和最后一个?
How about using the CSS selector
:first-child
and:last-child
to alter the first and last<div>
?如果您可以更改标记本身,那么我想我们可以有一个跨浏览器兼容的解决方案:
然后应用 css,如下所示:
If you can alter the markup itself, then I guess we can have a cross browser compatible solution:
and then apply the css like:
为最后一个块分配一个名为“last”的类。
将每个块的 margin-right 设置为 1px。
将最后一个类的块的 margin-right 设置为 0。
.block.last { 右边距:0px; 像 forst-child 和 last-child这样
的伪选择器没有得到很好的支持,所以我认为这是最好的选择。
Assign a class for last block called 'last'.
The set margin-right of every block to 1px.
Set margin-right of block that has last class to 0.
.block.last { margin-right: 0px; }
Pseudo selectors like forst-child and last-child are not well supported so I think this is the best option you have.