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

如何居中含多元素的div?flex布局致元素重叠问题求助

解决方法

要实现div在页面居中,同时避免内部图片和文本重叠,只需调整两处关键CSS设置:

1. 让容器div在页面中居中

给body添加flex布局,使其成为居中容器,确保div在视口中垂直水平居中:

body {
  background-color: #d5e1ef;
  /* 添加以下代码 */
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
}

2. 调整div内部元素的排列方向

默认display:flex是横向排列,会导致内容挤在一起,需要改为垂直排列,并优化文本对齐:

div {
  width: 320px;
  background-color: white;
  border-radius: 20px;
  overflow: hidden;
  padding: 16px;
  display: flex;
  /* 添加以下代码 */
  flex-direction: column;
  text-align: center;
  gap: 16px; /* 可选:给内部元素添加间距,排版更美观 */
}

修改后的完整代码

CSS

body {
  background-color: #d5e1ef;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
}

div {
  width: 320px;
  background-color: white;
  border-radius: 20px;
  overflow: hidden;
  padding: 16px;
  display: flex;
  flex-direction: column;
  text-align: center;
  gap: 16px;
}

img {
  max-width: 100%;
  border-radius: 10px;
}

/* 可选:优化文本样式,让排版更协调 */
h1 {
  font-size: 20px;
  margin: 0;
  color: #1f3251;
}

p {
  font-size: 15px;
  margin: 0;
  color: #7b879d;
}

HTML

<div>
  <img src="./image-qr-code.png" />
  <h1>Improve your front-end skills by building projects</h1>
  <p>
    Scan the QR code to visit Frontend Mentor and take your coding skills to the next level
  </p>
</div>

关键修改说明

  • body的min-height:100vh确保容器占满整个视口高度,配合justify-content:center和align-items:center实现div的垂直水平居中。
  • div的flex-direction:column将内部元素从横向排列改为垂直排列,彻底解决图片和文本重叠问题。
  • gap:16px给内部元素添加统一间距,提升排版美观度;text-align:center让文本居中对齐,符合QR卡片的常见设计。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:25:21