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

如何实现响应式子div.case_txt在父div中垂直水平居中?

子元素垂直水平居中解决方案

以下几种方案均可实现.case_txt在.case_btn内垂直水平居中,且适配不同屏幕尺寸:

方法1:Flexbox布局(推荐)

修改父元素.case_btn的样式,通过Flex属性快速实现居中,适配性强:

.case_btn {
  width: 90%;
  height: 20%;
  background: #838383;
  border: 1px solid white;
  margin-bottom: 20%;
  padding: 0px;
  /* 添加Flex布局属性 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.case_txt {
  border: 1px solid red;
  color: white;
  text-align: center; /* 子元素内文本水平居中(按需保留) */
  /* 移除margin: 0 auto; Flex已处理水平居中 */
}

若父元素height:20%未生效,需确保上级容器(如html、body)设置明确高度:

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

方法2:Grid布局

通过Grid属性一键实现双方向居中,代码更简洁:

.case_btn {
  width: 90%;
  height: 20%;
  background: #838383;
  border: 1px solid white;
  margin-bottom: 20%;
  padding: 0px;
  /* 添加Grid布局属性 */
  display: grid;
  place-items: center; /* 同时实现水平+垂直居中 */
}

.case_txt {
  border: 1px solid red;
  color: white;
  text-align: center;
}

方法3:绝对定位+transform(兼容旧浏览器)

针对需要兼容低版本浏览器的场景,可使用该方案:

.case_btn {
  width: 90%;
  height: 20%;
  background: #838383;
  border: 1px solid white;
  margin-bottom: 20%;
  padding: 0px;
  position: relative; /* 父元素设为相对定位,作为子元素定位基准 */
}

.case_txt {
  border: 1px solid red;
  color: white;
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 偏移自身尺寸的50%实现精准居中 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:05:08