使用jQuery使子DIV大于父DIV

时间:2015-03-24 10:23:01

标签: javascript jquery html css css3

我想让固定宽度为父100%宽度的Child Div,如下所示:

Child Div 100% width of a fix width Parent

我知道有很多关于此的问题,遗憾的是没有人回答在儿童DIV下面没有正确显示内容的强调问题。

我知道使用CSS这可以部分实现:

.child-div {
    position: absolute;
    left: 0;
    right: 0;
}
.parent-div {
    position: static;
    max-width: 900px;
}

我在CMS中工作,这意味着我无法定制HTML来打开和关闭包装器,这当然是正确的解决方案。但我知道有很多人因为其他许多原因需要这样做。

另一个问题是,通过使用此方法,子项下面的所有内容都显示在.child-div后面,它不会位于下方。我明白这一点,因为通过使它绝对不再是内容的流程。

我理解为什么这不起作用,但有没有使用jQuery或Javascript的解决方案?

http://jsfiddle.net/d4tjkwnc/

4 个答案:

答案 0 :(得分:1)

只使用CSS并且没有绝对位置(如果你不关心IE8 support)就可以解决这个问题。

您的CSS应如下所示:

.child-div {
    left: 0;
    right: 0;
    border: 1px solid blue;
    height: 100px;
}
.parent-div {
    position: static;
    max-width: 900px;
    border: 1px solid black;
    height: 300px;
    margin: 0 auto;
}

@media (min-width: 900px) {
    .child-div {
        /* 450px is 900px/2 and 50vw is 50% of the viewport */
        margin: 0 calc(450px - 50vw); 
    }
}

你基本上使用负边距和calc()“函数”的力量,因为你没有使用绝对位置,所以你解决了所有问题。

http://jsfiddle.net/wfverf6d/1/

答案 1 :(得分:0)



*{margin:0 ;padding: 0}
.parent{width:960px; margin:0 auto;height: 750px; border: 1px solid black; }
.child{position: absolute;top:0;width: 100%; margin-top: 100px; border: 1px solid red;height: 100px;background-color: #fff;}

<div class="parent">
  <div class="child"></div>
</div>
&#13;
&#13;
&#13;

尽管需要,尽量避免使用位置。我根据你给出的线框制作了这个标记。

答案 2 :(得分:0)

.container {
  position : absolute;
  top : 0;
  bottom : 0;
  left : 25%;
  right : 25%;
  border : solid 2px black;
  border-radius : 2px;
}

.contained {
  border : solid 2px blue; 
  border-radius : 2px;
  position : fixed; /* here is the trick */
  top : 10%;
  left : 0;
  right : 0;
  height : 100px;
}
<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <div class="container">
      <div class="contained">
        
      </div>
    </div>
  </body>
</html>

使用position : fixed来实现目标。在已使用absolute的{​​{1}}中使用div时,它只会粘贴到容器div的角落。 absolute适用于整个视口。

答案 3 :(得分:0)

我就是这样做的:

假设这个标记:

<div class="parent">
    [content before]
    <div class="child"></div>    
    [content after]
</div>

这是CSS:

// for decorative purpose
div{min-height:100px;padding:50px 0;}

.parent {
    width:900px; margin:0 auto; // parent width (in px or %) and centering
    background-color:grey;
}
.child {        
    background-color:blue;
}
@media (min-width: 900px) {
    .child {
        position:relative; left:50%; // centered position
        width:100vw; // set width to 100% of the view port width
        margin-left:-50vw;// margin left of 50% of the viewport width
    }
}

JSFiddle:https://jsfiddle.net/whytk3xt/4/