Container Div不包含内部div

时间:2015-12-29 14:21:15

标签: html css

这是我的代码:

.right {
  position: absolute;
  right: 0px;
  width: 300px;
  border: 3px solid #73AD21;
  padding: 10px;
}
body {
  margin: 0;
  padding: 0;
}
#a {
  border: 3px solid #73AD21;
  position: relative;
  width: 100%;
}
<div id="a">
  <div class="right">
    <p>This is a Test.</p>
  </div>
</div>

请看小提琴:

https://jsfiddle.net/9d8wq0by/

4 个答案:

答案 0 :(得分:4)

它不包含孩子,因为绝对定位的元素已从正常流中移除。作为替代方法,您可以将元素浮动到右侧,然后将clearfix添加到父元素。

您还可以将box-sizing: border-box添加到这两个元素中,以便考虑边框并将其包含在元素高度/宽度计算中。

Updated Example

.right {
  float: right;
  width: 300px;
  border: 3px solid #73AD21;
  padding: 10px;
}
#a {
  border: 3px solid #73AD21;
  position: relative;
  width: 100%;
  overflow: auto;
}
#a, .right {
  box-sizing: border-box;
}

或者,您可以添加margin-left: auto

,而不是将元素浮动到右侧

Updated Example

.right {
  width: 300px;
  border: 3px solid #73AD21;
  padding: 10px;
  margin-left: auto;
}

答案 1 :(得分:3)

参见this小提琴

您为position:absolute指定了.right,为position:relative指定了#a,这是错误的。

您必须同时指定两者,父母和子女具有相同的定位,或者父母应该绝对定位且孩子相对。

请参阅fiddle

.right的更新CSS如下

.right {
    position: relative;
    right: 0px;
    width: 300px;
    border: 3px solid #73AD21;
    padding: 10px;
}

<强>更新

要使.right div保持在右侧,您只需在float:right的CSS中添加.right

答案 2 :(得分:2)

父级应为absolute,子级为relative。你做了相反的事。

父母也可以是relative

.right {
    position: relative;
    float: right; //You need this to make the child glue to the right of the parent
    right: 0;
    max-width: 300px;
    padding: 10px;
}

body {
    margin: 0;
    padding: 0;
}

#a
{
 border: 3px solid #73AD21;
 position:  absolute;
 width:100%;

}
<html>
<head>
</head>
<body>
<div id="a">
<div class="right">
  <p>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.</p>
</div>
</div>

</body>
</html>

答案 3 :(得分:1)

结合上面的回答,你可以使用float:right方法,你可以添加css来清除浮动。所以新的.right CSS和clearfix将是:

.right {
float:right;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}

a:after {
 visibility: hidden;
 display: block;
 font-size: 0;
 content: " ";
 clear: both;
 height: 0;
 width: 100%;
}