margin-right 和 left 在 overflow-float div 方面以不同的方式工作

margin-right and left works in different way regards to overflow-float divs

    <body>
        <div class="content">
           <div class="content-sidebar">
                content-sidebar
            </div>
            <div class="content-main">
                content-main
            </div>
        </div>
    </body>

上面是html代码,下面是css代码。

body {
    margin: 0;
    padding: 0;
}

.content {
    background-color: yellow;
}

.content-sidebar {
    background-color: red;
    float: right;
    margin-left: 30px;
}

.content-main {
    background-color: green;
    height: 300px;
    overflow: hidden;
}

隐藏溢出 属性 在 .content-main 中创建新的块格式化上下文,因此 .content-sidebar 和 .content-main 完全处于不同的上下文中。

所以我认为 .content-main 上的 margin-right:30px 会起作用。

但它仅在 .content-sidebar(左边距)中有效。

已编辑))

此外,我使用 chrome 开发工具对其进行了检查,并且 margin-right on main div 与浏览器进行了交互。 (不带侧边栏)。但是浮动的侧边栏与主要 div 交互。这是为什么..?

首先要指出的是你说:

overflow hidden property creates new block formatting context in the .content-main, so .content-sidebar and .content-main are totally in different context.

这是不正确的。 overflow hidden 属性 为其内容 建立了一个新的块格式化上下文 。它不会影响它所在的​​上下文。因此 .content-sidebar.content-main 处于同一上下文中。这与下面的引述有关。

CSS 2.2 section 9.5 Floats 说:

The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context (such as an element with 'overflow' other than 'visible') must not overlap the margin box of any floats in the same block formatting context as the element itself. If necessary, implementations should clear the said element by placing it below any preceding floats, but may place it adjacent to such floats if there is sufficient space. They may even make the border box of said element narrower than defined by section 10.3.3.

这里我们有 "must not overlap the margin box of any floats" 这就是为什么边栏上的 margin-left 将主要部分与它隔开的原因。但是我们也有 "make the border box of said element narrower" - 注意边框框,而不是边距框,所以不需要定位 main 的边距,这样它就不会与浮动框重叠侧边栏。