【问题标题】:Set space between divs设置 div 之间的空间
【发布时间】:2012-04-20 15:05:10
【问题描述】:

我有两个这样的 div:

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

这是我的 CSS:

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

}

#right
{
    float: right;
}

我希望 div 之间的空间为 40 像素。我尝试在我的 css 中添加填充、边距和宽度,但我认为它没有将填充设置为正确的 40 像素。怎么做?

【问题讨论】:

    标签: css asp.net-mvc


    【解决方案1】:

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

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

    你也可以组合子伪选择器:

    div:not(:first-child):not(:last-child) {
      margin-left: 20px;
      margin-right: 20px;
    }
    

    【讨论】:

      【解决方案2】:

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

      #left{
          float: left;
          margin-right: 40px;
      }
      #right{
         float: left;
      }
      

      【讨论】:

        【解决方案3】:

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

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

        我们正在利用 + css 选择器。它只选择紧跟在&lt;div&gt; 元素之后的&lt;div&gt; 元素。

        注意:我们在这里设置的是margin-left 而不是margin-right

        【讨论】:

          【解决方案4】:

          两个div之间需要一个gutter,gutter可以做成如下

          边距(装订线)= 宽度 - 装订线尺寸 例如 margin = calc(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>
          

          【讨论】: