【问题标题】:Consider floated elements for the width of blocks考虑块宽度的浮动元素
【发布时间】:2014-05-28 03:34:53
【问题描述】:

想象一下以下标记 (link to jsFiddle):

<div style="float: right; width: 200px; height: 200px; background-color: red; margin: 0 20px 0 30px;">
     Block 1
</div>

<div style="height: 100px; background-color: green;">Block 2</div>

因为第一个块是浮动的,所以第二个块占据了整个可用空间的宽度,就好像块 1 没有定义一样。我需要为第二个块设置什么,使其宽度最大为块 1 的空间减去块 1 的左边距?

最终结果应该类似于this,其中我在第二个块中使用了display: flex。但在我的情况下,我不能使用这个解决方案,因为第二个块包含一个看起来很难看的段落display: flex

注意:在我的例子中(为 wiki 编写模板)我可以更改第二个块的 CSS!

【问题讨论】:

    标签: html css css-float width


    【解决方案1】:

    给块二的右边距等于块一的宽度和边距:

    <div style="height: 100px; background-color: green;margin-right:230px;">Block 2</div>
    

    jsFiddle example

    (旁注:尽可能避免使用内联 CSS)

    【讨论】:

      【解决方案2】:

      不使用flex,只需将overflow: auto 添加到块2:

      <div style="height: 100px; background-color: green; overflow: auto;">
          Block 2
      </div>
      

      查看演示:http://jsfiddle.net/PXuWB/

      这种方法的优点是您不必指定边距的确切长度,这在响应式设计中更有用。

      通过设置overflow: auto,您可以创建一个块格式上下文,以防止内容与任何相邻的浮动元素交互。

      参考:http://www.w3.org/TR/CSS21/visuren.html#block-formatting

      【讨论】:

        猜你喜欢
        • 2012-03-08
        • 1970-01-01
        • 2012-04-21
        • 1970-01-01
        • 1970-01-01
        • 2017-05-26
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        相关资源
        最近更新 更多