【问题标题】:Can you make a child div larger than parent without position absolute你可以在没有绝对位置的情况下让一个子 div 比父级大吗
【发布时间】:2013-12-11 10:59:16
【问题描述】:

所以基本上我想要做的是在一个大于其父 div 的页面上有一两个 div。通常我会重组整个网站,但这将是一项艰巨的任务。

我不希望它们是绝对位置的原因是容器高度会被搞砸,这会导致绝对位置与某些 div 重叠。

两个div比父div大的原因是容器div不能大于1200px时,它们必须是浏览器的宽度。

【问题讨论】:

    标签: html css css-position


    【解决方案1】:

    是的!

    不仅如此,我们还可以使用vwcalc 做得更好。

    只需使用vw(百分比视口单位)将子元素的宽度设置为视口宽度的 100%,然后将其左边距设置为基于此计算的负值,减去包装。除了父级的可选max-width 之外,其他所有内容都是自动计算的。可以动态改变父容器的宽度,子容器会根据需要自动调整大小和对齐,不会被定位。

    body,
    html,
    .parent {
      height: 100%;
      width: 100%;
      text-align: center;
      padding: 0;
      margin: 0;
    }
    .parent {
      width: 50%;
      max-width: 800px;
      background: grey;
      margin: 0 auto;
      position: relative;
    }
    .child {
      width: 100vw;/* <-- children as wide as the browser window (viewport) */
      margin-left: calc(-1 * ((100vw - 100%) / 2));/* align left edge to the left edge of the viewport */
      /* The above is basically saying to set the left margin to minus the width of the viewport MINUS the width of the parent, divided by two, so the left edge of the viewport */
      height: 50px;
      background: yellow;
    }
    <div class='parent'>
      parent element
      <div class='child'>child element</div>
    </div>

    【讨论】:

    • 出色的解决方案,正是我想要的。你用这个优雅的解决方案为我省去了很多麻烦。
    • 大哥帮了大忙..你不知道你解决了我多大的麻烦。非常感谢。
    • 不错的解决方案。糟糕的是,这个答案比这里的“绝对位置”答案不受欢迎(查看,赞成......)stackoverflow.com/questions/5581034/…
    【解决方案2】:

    试试这个小提琴

    http://jsfiddle.net/stanze/g2SLk/

    .wrapper {
        width: 400px;
        border: 1px solid #f00;
        min-height: 153px;
    }
    .wrapper-child-1 {
        float: left;
        border: 1px solid #ccc;
        width: 195%;
        min-height: 262px;
    }
    
    <div class="wrapper">
      <div class="wrapper-child-1"> </div>
    </div>
    

    【讨论】:

      【解决方案3】:

      您也可以使用边距来实现此目的:http://jsfiddle.net/MEc7p/1/

      div{
      outline: 2px solid red;
      }
      #outer{
      width: 200px;
      height: 400px;
      }
      #inner{
      width: 600px;
      height: 200px;
      margin: 0 -20px;
      outline: 1px solid green;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 2013-01-05
        • 2012-02-08
        • 2020-09-29
        • 2015-05-19
        相关资源
        最近更新 更多