绝对定位方法:
(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)完整例子代码:
<!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>子元素高度与父元素一致</title> <style> .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; } </style> </head> <body> <div class="parent"> <div class="left"> 左侧 left 不定高,parent的高度随着左侧left 的高度变化而变化,右侧也跟着变 </div> <div class="right"> 这边的高度跟父元素高度一致 </div> </div> </body> </html>
(5)效果
(6)问题来了:
如果右侧的子元素高度超出了.parent,怎么办?
.right-inner { background: limegreen; height: 1024px; }
<div class="right"> <div class="right-inner">right的子元素,高度为1024px,会撑破容器,给.right加上 overflow:auto 就防止溢出了</div> </div>
效果图如下:
完整代码:
<!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>子元素高度与父元素一致</title> <style> .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; height: 100%; overflow: auto; background: #ccc; } .right-inner { background: limegreen; height: 1024px; } </style> </head> <body> <div class="parent"> <div class="left"> 左侧 left 不定高,parent的高度随着左侧left 的高度变化而变化,右侧也跟着变 </div> <div class="right"> <div class="right-inner">right的子元素,高度为1024px,会撑破容器,给.right加上 overflow:auto 就防止溢出了</div> </div> </div> </body> </html>
(7)其他资源
http://stackoverflow.com/questions/3049783/how-to-make-a-floated-div-100-height-of-its-parent
到此这篇关于CSS子元素跟父元素的高度一致的实现方法的文章就介绍到这了,更多相关CSS子元素父元素高度内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!
用什么代码实现?不允许有白色底色产生,因为手机高度不一样 设计图要标准(750...
问题描述 按钮样式为图标+文字,在使用flex布局写垂直居中时,iphone7手机上文字...
复制代码 代码如下: html !--混合框架的布局: 要想实现复杂的页面布局,只需在f...
首先提示,处于安全的需要JavaScript不能直接访问本地资源文件,那怎么办呢?下...
1. 给logo添加替代文本 这样有两个好处:屏幕阅读器能识别logo图片代表的含义,...
创业公司常常能给我们带来惊喜,不拘一格的工作方式,别开生面的商业模式,独树...
em是何物? em指字体高,任意浏览器的默认字体高都是16px。所以未经调整的浏览器...
大家好,我是民工哥。 一提到监控系统,大家很快就能想到 Zabbix 、 Prometheu s...
最近在开发中遇到的需求是:微信扫描课件二维码,播放其对应的课件视频 设计流程...
一、前言 在了解加密原理前,我们来看看这样一个故事。 小红和小明是情侣,一天...