CSS 设置div之间的空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10052922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:32:01  来源:igfitidea点击:

Set space between divs

cssasp.net-mvc

提问by petko_stankoski

I have two divs like this:

我有两个这样的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>

And here is my css:

这是我的 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?

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

回答by David Salamon

For folks searching for solution to set spacing between Ndivs, here is another approach using pseudo selectors:

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

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

You can also combine child pseudo selectors:

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

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

回答by benni_mac_b

Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.

以相同的方式浮动它们并添加 40px 的边距。如果您有 2 个元素以相反的方式浮动,那么您的控制就会少得多,并且包含元素将决定它们相距多远。

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

回答by zawhtut

You need a gutter between two div gutter can be made as following

您需要在两个 div 装订线之间设置一个装订线,如下所示

margin(gutter) = width - gutter size E.g margin = calc(70% - 2em)

margin(gutter) = width - gutter size 例如边距 = 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>