如何实现图片上文字垂直居中,超出高度时触发overflow-y不被截断
问题原因
你遇到的两个问题都是flex布局的默认特性导致的:
- 第一种写法中overflow滚动容器是flex的直接子元素,容器本身撑满了父层高度,内部文字默认顶对齐,自然无法居中
- 第二种写法中overflow加在了flex容器本身,当内容高度超出容器高度时,
align-items: center会让内容从上下两端同时溢出,顶部内容会被裁剪到可视区域外,滚动也无法访问到被裁剪的部分
修复方案
只需要在flex容器和文字内容之间加一层自适应容器,同时调整overflow的位置即可,完整代码如下:
<div class="w-full text-md border border-red-600"> <div class="relative"> <img class="w-full h-96" src="https://i.imgur.com/hAodNjT.jpg" /> <!-- 外层绝对定位flex容器,不需要加overflow --> <div class="flex absolute h-full top-0 w-full sm:w-1/2" style="background-color: rgba(255, 255, 255, 0.7)"> <!-- 新增的文字容器,my-auto实现垂直居中,max-h-full限制高度,overflow-auto实现超出滚动 --> <div class="w-full my-auto max-h-full overflow-y-auto"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </div> </div> </div> </div>
实现逻辑
- 文字内容较短时,
my-auto会自动将内容垂直居中对齐 - 文字内容超出父容器高度时,
max-h-full会限制文字容器的高度不超过背景图高度,超出部分自动触发纵向滚动,不会出现顶部内容被裁剪的问题
内容的提问来源于stack exchange,提问作者catra
相关产品推荐
相关产品推荐

