如何在带垂直滚动的父div中垂直居中子div?CSS/JS实现方案
实现滚动容器可视区域内的子元素垂直居中
我来帮你搞定这个需求——要让左右两个子div始终停留在滚动容器的可视区域垂直中间(而非容器总高度的中间),同时支持自适应高度、内容变化时保持居中,我们需要调整定位方式,具体方案如下:
核心思路
- 抛弃原有的
float布局,改用position: sticky让子元素锚定滚动容器的可视区域 - 结合
top: 50%和transform: translateY(-50%)实现自适应高度的垂直居中,这种方式能自动适配子元素的高度变化 - 确保滚动容器作为sticky元素的定位上下文
修改后的完整代码
CSS部分
.overlay_background { position: fixed; overflow: initial; height: 0; width: 0; left: 0; top: 200px; transition: 0.7s ease; z-index: 1; } .overlay_ws_container { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; height: 80vh; width: 900px; overflow-y: auto; background-color: #e7e7e7; border-radius: 5px; box-shadow: 0px 0px 32px 1px rgba(0, 0, 0, 1); text-align: center; /* 新增:作为sticky元素的定位上下文 */ position: relative; } /* 重写左右子元素的定位逻辑 */ .overlay_background .left_img { position: sticky; top: 50%; transform: translateY(-50%); left: 20px; width: 200px; padding: 20px 0; /* 移除float和固定min-height,让高度自适应内容 */ } .overlay_background .right_img { position: sticky; top: 50%; transform: translateY(-50%); right: 20px; width: 200px; padding: 20px 0; /* 移除float和固定min-height */ } .overlay_background .text_overlay_container { height: auto; width: 400px; text-align: left; padding: 10px; word-wrap: break-word; margin: 0 auto; white-space: pre-line; /* 确保中间内容不会被左右元素遮挡 */ position: relative; z-index: 0; } .img_size_200 { width: 200px; height: 200px; transition: transform .2s; cursor: pointer; }
HTML部分
(HTML结构无需改动,保持你原有的代码即可)
<div class="overlay_background" id="overlay_background_id"> <img src="hello" style="width: 40px;cursor: pointer; position: absolute; right: 10px; top: 10px;"> <div class="overlay_ws_container"> <div class="left_img"> <img src="" class="img_size_200"> <img src="" class="img_size_200"> </div> <div class="right_img"> <img src="" class="img_size_200"> <img src="" class="img_size_200"> </div> <h1 style="font-size: 30px"></h1> <div class="text_overlay_container"> </div> <div> <button class="btn_ws" id="btn_sold_id" style="display: none; cursor: not-allowed">Sold out</button> </div> Quantity: <input id="inp_quantity_id" type="number" class="inp_quantity" value="1"> <div style="margin-top: 5px;"> <h1 style="color: inherit; font-weight: bold" id="prices"></h1> </div> <div> <button class="btn_ws" id="btn_ws" style="display: none">Add to basket</button> </div> </div> </div>
关键改动说明
- 定位上下文设置:给
.overlay_ws_container添加position: relative,确保sticky元素以这个滚动容器为参考,而不是整个页面 - sticky居中实现:
position: sticky让元素在滚动时保持在可视区域的指定位置,top: 50%让元素顶部对齐可视区域中点,transform: translateY(-50%)则让元素自身垂直居中——这个方法的优势是不管子元素高度是多少(auto自适应),都能完美居中 - 移除冗余属性:删掉了
float和min-height,让子元素高度完全由内容决定,同时避免float带来的布局冲突 - 层级处理:给中间文本容器设置
z-index: 0,确保滚动内容不会被左右sticky元素遮挡
这样修改后,当你滚动.overlay_ws_container时,左右两个子div会始终停留在当前可视区域的垂直中间位置;如果子div里新增/删除图片,高度变化后也会自动保持居中状态。
内容的提问来源于stack exchange,提问作者user9697902
相关产品推荐
相关产品推荐

