[随笔] 指定div内-让文字在图片上方且水平垂直居中

本文介绍了如何在CSS中使文字在指定div内的图片上方保持水平垂直居中,并在图片压缩时保持等比例缩小。通过使用定位和CSS3的flex布局,可以实现这个效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求 —— 在一个指定的div(cotainer)内,要实现:

  • 图片撑满div
  • 文字水平垂直居中
  • 文字在图片上方
  • 压缩时底下图片能等比例缩小 -> 可设置最小值

实现 —— 直接上代码:

<div class="cotainer">
  <img src="@/../static/img/img_manage_logoBg.png" alt="bg">
  <div class="textBox">
	<p>标题</p>
	<a href="" class="btn">按钮</a>
  </div>
</div>
.container {
  position: relative; /*父级容器相对定位*/
  margin: 0 10px;
}

.container img {
  /* 图片撑满父级div */
  width: 100%;
  height: 100%;
}

 /* 文字包裹于div + 绝对定位 */
.textBox {
  width: 100%;
  position: absolute;
  /* left: 50%; */
  top: 50%;
  /* transform: translateX(-50%); */
  transform: translateY(-50%);
  /* 文字div内用flex布局 */
  display: flex;
  flex-flow: column nowrap;
  justify-content: center; /*垂直方向居中*/
  align-items: center;
}
.textBox p {
  width: 100%; /*宽度撑满,使用text-align: center水平居中*/
  /* 以下根据需要设置 */
  height: 32px;
  font-size: 32px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #000;
  letter-spacing: 1px;
  line-height: 32px;
  text-align: center;
}
.textBox a {
  display: block;
  width: 134px; /*宽度固定,flex布局实现水平居中*/
  height: 36px;
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #007BDB;
  /* letter-spacing: 1px; */
  line-height: 22px;
  text-align: center;
  text-decoration: none;
  border: 1px solid #007BDB;
  border-radius: 20px;
  padding: 5px;
  margin-top: 5%;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值