html⾏⾼与⽗div⼀样,CSS⼦元素跟⽗元素的⾼度⼀致的实现
⽅法
绝对定位⽅法:
(1)将⽗元素设置为相对定位,不写⽗元素的⾼度时,会随着左边的⼦元素⾼度变化⽽变化
.parent {
/*关键代码*/
position: relative;
/*其他样式*/
width: 800px;
color: #fff;
font-family: "Microsoft Yahei";
text-align: center;
}
(2)左边⼀个元素有个最⼩⾼度的情况
.left {
min-height: 700px;
width: 600px;
}
(3)右边元素要想跟⽗元素的⾼度是⼀致,那么可以⽤绝对定位这样设置,如果不想同时写top和bottom,写⼀个时,再写上height:100%,也可以达到⼀样的效果
.right {
/*关键代码*/
width: 200px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
/*其他样式*/
background: #ccc;
}
(4)完整例⼦代码:
⼦元素⾼度与⽗元素⼀致
.parent{
position: relative;
background: #f89;
width: 800px;
color: #fff;
font-family: "Microsoft Yahei";
text-align: center;
}
.left {
min-height: 700px;
width: 600px;
}
.right {
width: 200px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
background: #ccc;
}
左侧 left 不定⾼,parent的⾼度随着左侧left 的⾼度变化⽽变化,右侧也跟着变这边的⾼度跟⽗元素⾼度⼀致
(5)效果
(6)问题来了:
如果右侧的⼦元素⾼度超出了.parent,怎么办?
.right-inner {
background: limegreen;
height: 1024px;
}
right的⼦元素,⾼度为1024px,会撑破容器,给.right加上 overflow:auto 就防⽌溢出了效果图如下:
完整代码:
⼦元素⾼度与⽗元素⼀致
.parent{
position: relative; background: #f89;
width: 800px;
color: #fff;
font-family: "Microsoft Yahei"; text-align: center;
}
.left {
absolute relativemin-height: 700px;
width: 600px;
}
.right {
width: 200px;
position: absolute;
top: 0;
right: 0;
height: 100%;
overflow: auto;
background: #ccc;
}
.right-inner {
background: limegreen;
height: 1024px;
}
左侧 left 不定⾼,parent的⾼度随着左侧left 的⾼度变化⽽变化,右侧也跟着变
right的⼦元素,⾼度为1024px,会撑破容器,给.right加上 overflow:auto 就防⽌溢出了(7)其他资源

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。