如何将文本放置在网格布局内div元素的底部?
问题描述
尝试将文本放置在包含它的div元素底部,但设置position: relative; bottom: 0无效,使用垂直对齐也没有效果。
原代码示例
CSS
* { box-sizing: border-box; } body { padding: 0; margin: 0; } .mainContainer { display: grid; width: 100vw; height: 100vh; place-items: center; } .subContainer { display: grid; grid-template-columns: 20% 80%; width: 60%; } .anotherDiv { background-color: rgb(195, 171, 171); } img { width: 100%; height: auto; } .textForBottom { position: relative; bottom: 0; }
HTML
<div class="mainContainer"> <div class="subContainer"> <img src="https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg" alt="cat" /> <div class="anotherDiv"> <span class="textForBottom"> This text should be at the bottom in the div that contains it </span> </div> </div> </div>
解决方案
position: relative只会让元素相对于自身原位置偏移,无法实现定位到父容器底部的效果。以下是几种可行的实现方式:
方法1:Flexbox布局
给父容器.anotherDiv设置Flex布局,通过属性控制文本位置:
.anotherDiv { background-color: rgb(195, 171, 171); display: flex; justify-content: flex-start; /* 水平方向靠左,可按需调整 */ align-items: flex-end; /* 垂直方向靠底部 */ min-height: 100%; /* 让父容器高度与左侧图片匹配 */ }
方法2:Grid布局
利用Grid布局的容器属性实现内容靠底:
.anotherDiv { background-color: rgb(195, 171, 171); display: grid; align-content: end; /* 让内容靠底部 */ min-height: 100%; }
方法3:绝对定位
给父容器设置相对定位,文本设置绝对定位:
.anotherDiv { background-color: rgb(195, 171, 171); position: relative; min-height: 100%; } .textForBottom { position: absolute; bottom: 0; left: 0; /* 可选,控制水平位置 */ }
注意:添加min-height: 100%是为了让.anotherDiv的高度与左侧图片保持一致,否则父容器高度仅由文本内容撑开,底部定位效果无法显现。
内容的提问来源于stack exchange,提问作者CupOfGreenTea
相关产品推荐
相关产品推荐

