是否可以使用纯CSS进行此操作?
感谢。
var main = document.getElementsByClassName('container');
for(var i = 0; i < main.length; i++) {
var height = main[i].childNodes[3].offsetHeight;
main[i].style.height = height+"px";
}
&#13;
.container {
width: 100%;
background: yellow;
position: relative;
margin-bottom: 10px;
}
.left-child {
width: 40%;
height: 120px;
background: red;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.right-child {
width: 60%;
height: 180px;
background: blue;
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 40%;
}
&#13;
<div class="container">
<div class="left-child">
</div>
<div class="right-child">
</div>
</div>
<div class="container">
<div class="left-child">
</div>
<div class="right-child">
</div>
</div>
&#13;
答案 0 :(得分:1)
喜欢这个吗?
我已将height
添加到.container
,因为孩子们绝对定位,他们不在文档的流程中,这意味着它就像.container
那样&n&n根本没有孩子。
对于height:100%
的{{1}},它是这样的,它取得了最近的相对定位元素的高度,即.right-child
.container
&#13;
.container {
width: 100%;
height: 200px;
background: yellow;
position: relative;
margin-bottom: 10px;
}
.left-child {
width: 40%;
height: 120px;
background: red;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.right-child {
width: 60%;
height: 100%;
background: blue;
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 40%;
}
&#13;
答案 1 :(得分:1)
您可以使用flexbox
执行此操作,只需将display: flex;align-items: center;
添加到.container
并移除position: absolute
和transform translate
内容并获得干净的CSS
.container {
background: yellow;
margin-bottom: 10px;
display: flex; /* added property */
align-items: center; /* added property */
}
.left-child {
width: 40%;
height: 120px;
background: red;
}
.right-child {
width: 60%;
height: 180px;
background: blue;
}
<div class="container">
<div class="left-child">
</div>
<div class="right-child">
</div>
</div>
<div class="container">
<div class="left-child">
</div>
<div class="right-child">
</div>
</div>
答案 2 :(得分:1)
另一种方式:
.container {
width: 100%;
background: yellow;
overflow:hidden;
margin-bottom: 10px;
}
.left-child {
margin-top:30px;
width: 40%;
height: 120px;
background: red;
float:left;
}
.right-child {
width: 60%;
height: 180px;
background: blue;
float:right;
}
答案 3 :(得分:1)
没有a2()
或position : relative
position : absolute
&#13;
.container {
width: 100%;
background: yellow;
margin-bottom: 10px;
display: inline-block;
}
.left-child {
width: 40%;
height: 120px;
background: red;
margin-top: 30px;
display:inline-block;
}
.right-child {
width: 60%;
height: 180px;
background: blue;
display:inline-block;
float: right;
}
&#13;