You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不使用position:absolute时将文本定位在div底部上方20%?

解决方案:用CSS Grid实现精准定位(无需绝对定位)

你遇到的问题核心是垂直margin/padding的百分比是基于父元素的宽度,而非高度——所以margin-top:80%计算的是父容器宽度的80%,远大于容器高度的80%,直接把文本推到了容器外面,被overflow:hidden隐藏了。

不用position:absolute的话,CSS Grid是最适合的方案,它能精准控制元素在容器内的位置,还不会打乱现有布局:

修改后的CSS代码

.featured_title {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  margin: auto;
  /* 移除原来的margin-top/bottom,改用Grid定位 */
  font-size: 4vw;
  color: #000;
  width: 65%;
  text-align: center;
  grid-row: 2; /* 把文本放到第二行 */
  align-self: start; /* 文本在第二行顶部对齐 */
}

.browser {
  width: 1366px;
  height: 768px;
}

.featured_box {
  max-height: 500px;
  overflow: hidden;
}

.banner {
  margin:auto;
  width: 80%;
  display: block;
  max-height: 500px;
  overflow: hidden;
}

.featured_image {
  overflow: hidden;
  position: relative;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  height: 500px;
  width: 100%;
  /* 添加Grid布局,分成80%和20%的两行 */
  display: grid;
  grid-template-rows: 80% 20%;
}

实现原理

  1. 给.featured_image设置display: grid,并通过grid-template-rows: 80% 20%把容器垂直分成上下两部分:上半部分占80%高度,下半部分占20%。
  2. 让.featured_title定位到第二行(grid-row:2),并设置align-self:start让文本在第二行的顶部对齐——这样文本就刚好位于容器底部上方20%的位置,完美符合你的需求。

这种方法的优势是:

  • 完全不需要绝对定位,不会干扰其他元素布局
  • 比例是基于容器高度计算的,响应式场景下(比如容器高度变化),文本位置会自动保持和底部的20%距离
  • 代码简洁直观,维护成本低

另一种可选方案:Flex布局

如果你更习惯用Flex,也可以这样实现:

.featured_image {
  /* 原有样式 */
  display: flex;
  flex-direction: column;
}

.featured_title {
  /* 原有样式 */
  margin-top: auto; /* 把文本推到容器底部 */
  transform: translateY(-20%); /* 往上移动容器高度的20% */
  /* 注意:如果容器高度是动态的,需要用CSS变量配合calc,比如:
  --container-height: 500px;
  transform: translateY(calc(-1 * var(--container-height) * 0.2));
  */
}

不过Grid的方法在比例控制上更直接,推荐优先使用。

内容的提问来源于stack exchange,提问作者Oful

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:07:34