你可以让一个比父母更大的子div没有位置绝对

时间:2013-11-26 10:40:38

标签: html css css3 css-position

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

我不希望它们位于绝对位置的原因是容器高度将被拧紧,这将导致位置绝对值与某些div重叠。

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

3 个答案:

答案 0 :(得分:35)

是的!

不仅如此,我们还可以使用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>

答案 1 :(得分:1)

您还可以使用边距来实现此目的: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;
}

答案 2 :(得分:0)

试试这个小提琴

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>