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

如何实现两个div垂直居中且各自背景填充半屏?

嘿,我来帮你搞定这个需求!要实现两个div垂直居中在页面,同时各自背景填充半屏,咱们只需要调整一下样式布局就行,具体方案如下:

实现步骤与代码

首先得确保页面的根元素能撑满整个视口,不然垂直居中的效果只会在内容高度里生效,然后再调整容器和子元素的样式:

完整CSS代码

/* 清除默认边距,让根元素撑满整个视口高度 */
html, body {
  height: 100%;
  margin: 0;
}

.contenedor {
  display: flex;
  /* 让容器占满整个视口高度 */
  height: 100vh;
  /* 垂直居中子元素 */
  align-items: center;
  /* 容器宽度拉满视口 */
  width: 100%;
}

.español {
  background: red;
  /* 让背景填充整个容器高度 */
  height: 100%;
  /* 平分容器宽度,占50% */
  flex: 1;
  /* 让内部文字在半屏区域内垂直水平居中 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.english {
  background: blue;
  height: 100%;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

a {
  text-decoration: none;
  color: white; /* 深色背景配白色文字更清晰,可按需调整 */
  font-size: 50px;
}

对应的HTML(无需修改你的原有结构)

<div class="contenedor">
  <div class="español">
    <a href="/es">Español</a>
  </div>
  <div class="english">
    <a href="/en">English</a>
  </div>
</div>

关键改动说明

  • html, body { height: 100%; margin: 0; }:消除浏览器默认的边距,让根元素高度完全覆盖视口,这样容器的全屏高度才会生效。
  • .contenedor { height: 100vh; width: 100%; }:让父容器占满整个页面的高度和宽度,作为两个子div的承载容器。
  • 子元素的flex: 1:让两个div自动平分父容器的宽度,各占50%;height: 100%则让它们的背景填充整个父容器的高度,实现半屏背景的效果。
  • 子元素内部添加的flex布局:让链接文字在各自的半屏区域内也实现垂直水平居中,提升视觉体验。
  • 给a标签加白色文字:在红蓝背景上更易读,你可以根据喜好改成其他颜色。

这样调整后,就能完美实现你想要的效果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:02:00