【问题标题】:CSS Fluid layout with containing div margin or padding causes overflow包含 div 边距或填充的 CSS 流体布局导致溢出
【发布时间】:2013-02-12 07:27:49
【问题描述】:

我有一个jsfiddle ,其中最外面的包装 div 有 100% 的宽度。我想创建内部 div(tb_margin 或 tb_padding),其内容应从左侧 40px 开始。我尝试了边距和填充来创建这个 40px 的左间距,但在这两种情况下,由于宽度为 100%,实际 div 会从右侧伸出。

我希望标签包含在一个 div(tb_margin 或 tb_padding)中,它从左侧偏移 40 像素,但应该延伸到整个宽度直到右边框。

我不想将溢出:隐藏在(tb_margin 或 tb_padding)中,因为这样做会在选项卡过多时隐藏选项卡。理想情况下,选项卡应该换行到 (tb_margin 或 tb_padding) 包含的下一行。

<h1>hello</h1>
<div style="width:100%;height:100px;border: 1px solid red">
    <div style="width:100%;height:50%; border: 1px solid blue">
        <div style="height:100%;width:150px;float:left; border:1px solid yellow"> logo</div>
        <div style="float:right;border:1px solid green;"> User| 13-Nov-13| Logout </div>
    </div>
    <div id="tb_margin" style="width:100%;margin-left:40px;border:1px solid green">tabbbs with margin here </div>
    <div id="tb_padding" style="width:100%;padding-left:40px;border:1px solid grey">tabbbs with padding here </div>
</div>

我真的希望 CSS 框布局更直观,还是我遗漏了什么

【问题讨论】:

    标签: html css boxlayout


    【解决方案1】:

    box-sizing 来救援!

    #tb_padding {
      width:100%;
      padding-left:40px;
      border:1px solid grey;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
    }
    

    这是演示:http://jsfiddle.net/pavloschris/nepC3/25/ 还有一些信息:https://developer.mozilla.org/en-US/docs/CSS/box-sizing

    【讨论】:

    • +1 很好地修复了填充——尽管盒子大小会产生这种影响,但我不会有这种影响——可惜它似乎对边距不起作用。
    【解决方案2】:

    你想要达到的最简单的方法就是不在边距或填充的 div 上指定width: 100%。默认情况下,所有 div 都显示为 block,这意味着它们将拉伸以填充剩余的水平空间。

    实际指定width: 100% 的问题是,正如您所发现的,水平填充和边距是在宽度计算之上添加的 - 如果您未指定宽度,浏览器会自动计算宽度需要填充空间,这可能不是它的父级的100%。

    以后最好只在真正需要时才应用width: 100%(例如在使用浮点数时),如果可以避免指定尺寸,最好避免指定尺寸。

    <h1>hello</h1>
    <div style="width:100%;height:100px;border: 1px solid red">
      <div style="width:100%;height:50%; border: 1px solid blue">
        <div style="height:100%;width:150px;float:left; border:1px solid yellow">
          logo
        </div>
        <div style="float:right;border:1px solid green;">
          User| 13-Nov-13| Logout
        </div>
      </div>
      <div id="tb_margin" style="margin-left:40px;border:1px solid green">
        tabbbs with margin here
      </div>
      <div id="tb_padding" style="padding-left:40px;border:1px solid grey">
        tabbbs with padding here
      </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2010-10-11
      • 1970-01-01
      • 2020-10-27
      • 2012-06-13
      • 1970-01-01
      • 2014-03-24
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多