35

I have two divs like this:

<section id="main">
        <div id="left">
            <asp:ContentPlaceHolder ID="left" runat="server" />
        </div>
        <div id="right">
            <asp:ContentPlaceHolder ID="right" runat="server" />
        </div>
</section>

And here is my css:

#left
{
    float: left;
    margin-right: 17px;

}

#right
{
    float: right;
}

I want the space between the divs to be 40px. I tried adding padding, margin and width in my css, but I think it didn't set the padding to correct 40px. How to do it?

4

4 回答 4

58

对于寻找设置Ndiv 之间间距的解决方案的人们,这里是另一种使用伪选择器的方法:

div:not(:last-child) {
  margin-right: 40px;
}

您还可以组合子伪选择器:

div:not(:first-child):not(:last-child) {
  margin-left: 20px;
  margin-right: 20px;
}
于 2016-09-19T11:56:18.977 回答
32

以相同的方式浮动它们并添加 40px 的边距。如果您有 2 个元素以相反的方式浮动,您将拥有更少的控制权,并且包含元素将确定它们之间的距离。

#left{
    float: left;
    margin-right: 40px;
}
#right{
   float: left;
}
于 2012-04-07T08:22:40.573 回答
3

N div 之间间距的另一种解决方案是:

div + div {
  margin-left: 40px;
}

我们正在利用+css 选择器。它只选择<div>紧跟在元素之后的<div>元素。

注意:我们margin-left不在margin-right此处设置。

于 2021-07-26T20:14:53.810 回答
2

您需要两个 div 之间的排水沟,排水沟可以制作如下

边距(装订线)= 宽度 - 装订线尺寸 例如边距 = 计算(70% - 2em)

<body bgcolor="gray">
<section id="main">
        <div id="left">
            Something here     
        </div>
        <div id="right">
                Someone there
        </div>
</section>
</body>
<style>
body{
    font-size: 10px;
}

#main div{
    float: left;
    background-color:#ffffff;
    width: calc(50% - 1.5em);
    margin-left: 1.5em;
}
</style>
于 2018-07-22T18:06:45.947 回答