如何让Flex子元素占满父元素高度并实现区域整体可点击?
问题描述
我希望让包含“discussed”和图标的区域所在div能触发onClick事件,目前该div的点击功能正常,但存在空白间隙无法触发点击,想要消除此间隙,实现该区域整体可点击,请问该如何解决?
布局截图



当前代码
<div class="d-flex flex-column border border-primary mt-2 " style="max-width: 400px ; height: 130px;"> <div class="w-100 bg-warning text-center p-2"> <a href="">Somecontent from a map</a> </div> <div class="d-flex flex-column align-items-strentch " onclick="alert('hey')"> <div class="d-flex align-items-stretch justify-content-between pt-4 pb-2 px-2 flex-1 d-inline-block" > <text class="bg-warning "> discussed </text> <div onclick="alert('hey click me')">icons here</div> </div> </div> </div>
解决方案
问题根源在于带onclick的外层div没有填满父容器剩余高度,再加上Bootstrap类名拼写错误,导致空白区域不属于该div的可点击范围。按以下几点修改即可解决:
- 修正类名拼写:把
align-items-strentch改成align-items-stretch(这是Bootstrap的正确拉伸类,确保子元素占满容器宽度) - 给带
onclick的div添加h-100类,让它占满父容器的剩余高度,空白区域就会被纳入该div的点击范围 - 移除子div上的
d-inline-block类,它和d-flex属性冲突,会干扰布局拉伸效果
修改后的代码
<div class="d-flex flex-column border border-primary mt-2 " style="max-width: 400px ; height: 130px;"> <div class="w-100 bg-warning text-center p-2"> <a href="">Somecontent from a map</a> </div> <div class="d-flex flex-column align-items-stretch h-100" onclick="alert('hey')"> <div class="d-flex align-items-stretch justify-content-between pt-4 pb-2 px-2 flex-1" > <text class="bg-warning "> discussed </text> <div onclick="alert('hey click me')">icons here</div> </div> </div> </div>
修改完成后,包含“discussed”和图标的整个区域(包括之前的空白间隙)都能正常触发点击事件了。
内容的提问来源于stack exchange,提问作者Sohaib Ashraf
相关产品推荐
相关产品推荐

