将绝对定位的子级设置为父级的100%宽度(包括边框)

时间:2019-03-16 08:20:47

标签: html css

我有以下代码:

.parent , .child{
    border: 10px solid black;
    position: relative;
    box-sizing: border-box;
	background:green;
}
.child{
	background:blue;
    position: absolute;
    left: -10px;
    top: 100%;
    border-radius: 0px 0px 10px 10px;
	width:100%
}
<div class="parent">
Parent Element
<div class="child">
Child Element
</div>
</div>

虽然可以通过将宽度更改为calc(100% + 20px);来实现,但是还有一种更动态的方法来确保底部div与顶部对齐(不使用弹性框)?

3 个答案:

答案 0 :(得分:0)

既然您已经在使用left: -10px,为什么不直接使用right: -10px而不是设置宽度。

.parent , .child{
    border: 10px solid black;
    position: relative;
    box-sizing: border-box;
	background:green;
}
.child{
	background:blue;
    position: absolute;
    left: -10px;
    right: -10px;
    top: 100%;
    border-radius: 0px 0px 10px 10px;
}
<div class="parent">
Parent Element
<div class="child">
Child Element
</div>
</div>

答案 1 :(得分:0)

替代方法:不要让它成为孩子,而忽略顶部边框。

.parent , .child{
    border: 10px solid black;
    position: relative;
    box-sizing: border-box;
	background:green;
}
.child{
	background:blue;
    position: relative;
    border-top: 0 none;
    border-radius: 0px 0px 10px 10px;
}
<div class="parent">
Parent Element
</div>
<div class="child">
Child Element
</div>

答案 2 :(得分:0)

您可以使用父元素上的框阴影替换边框

.parent,
.child {
  padding: 10px;
  box-shadow: 0 0 0 10px inset black;
  position: relative;
  box-sizing: border-box;
  background: green;
}

.child {
  background: blue;
  position: absolute;
  left:0;
  top: 100%;
  border-radius: 0px 0px 10px 10px;
  width: 100%
}
<div class="parent">
  Parent Element
  <div class="child">
    Child Element
  </div>
</div>

另一个有背景的想法:

.parent,
.child {
  padding: 10px;
  position: relative;
  box-sizing: border-box;
  background: 
   linear-gradient(green,green) content-box,
   #000;
}

.child {
  background: blue;
  position: absolute;
  left:0;
  top: 100%;
  border-radius: 0px 0px 10px 10px;
  width: 100%;
  padding:0;
  border:10px solid;
}
<div class="parent">
  Parent Element
  <div class="child">
    Child Element
  </div>
</div>