Bootstrap添加h-100类后左列无法占满父div高度问题咨询
问题根因
你遇到的问题和块级元素属性无关,是两个布局规则冲突导致的:
- 你包裹左右两列的父容器(带
border border-dark的那层row)设置了align-items-center,这一Flex属性会强制所有子项高度收缩到自身内容高度,直接抵消了左列h-100的高度设置效果。 - Bootstrap的
h-100本质是height: 100%,这类百分比高度生效的前提是父元素有明确的固定高度值。你的父容器高度是由右侧图片的实际高度撑起来的,没有明确高度值,子元素的百分比高度找不到参考基准,自然不会生效。
修复方案
不需要用h-100,直接用Flex的拉伸属性实现即可:
- 删掉父容器的
align-items-center类 - 左列新增
align-self-stretch类自动拉伸到和父容器同高,再添加d-flex align-items-center justify-content-center实现内部文字的水平垂直居中
修改后的完整代码如下:
<div class="container vh-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <!-- 删掉了这层原有的align-items-center --> <div class="row col g-0 d-flex justify-content-center w-75 border border-dark"> <!-- 新增align-self-stretch、d-flex、align-items-center、justify-content-center,去掉无效的h-100 --> <div class="col-6 bg-secondary d-flex align-items-center justify-content-center align-self-stretch"> <h1 class="text-center">Hello There!</h1> </div> <div class="col-6"> <img src="images/ivy.jpg" alt="ivy" class="img-fluid" /> </div> </div> </div> </div>
内容的提问来源于stack exchange,提问作者redliz5808
相关产品推荐
相关产品推荐

