思路:父盒子不设置高度,随着左边盒子内容的变化而将父盒子高度撑开,此时父盒子高度等于左边盒子高度,然后再让右边盒子高度为父盒子高度的100%
用于测试,给左边盒子添加内容
<script>
const btn = document.querySelector('#btn')
const left = document.querySelector('.left')
btn.onclick = function () {
const value = left.textContent
left.textContent = value + '右边盒子高度随着左边盒子高度而变化'
}
</script>
使用 flex
<button id="btn">click</button>
<div class="father">
<div class="left">右边盒子高度随着左边盒子高度而变化</div>
<div class="right"></div>
</div>
.father {
background-color: pink;
display: flex;
}
.left {
margin-left: 20px;
padding: 10px;
width: 200px;
background-color: #fff;
}
.right {
margin-left: 300px;
width: 300px;
background-color: #ccc;
}
使用定位
.father {
background-color: pink;
position: relative;
}
.left {
margin-left: 20px;
padding: 10px;
width: 200px;
background-color: #fff;
}
.right {
left: 300px;
width: 300px;
background-color: #ccc;
position: absolute;
top: 0;
bottom: 0;
}