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

如何简单实现Div内文本的垂直水平居中?

如何简洁实现Div内文本的垂直居中?

我想把文本放在Div容器的正中央,但没找到简洁优雅的方案。用padding会让Div尺寸变大,不符合需求;嵌套Div的方式太繁琐,代码复杂后还容易出问题。希望找到类似textAlign:center的简单方法,实现垂直居中(不只是水平居中)。

相关代码如下:

import "./styles.css";

export default function App() {
  const style = {
    border: "1px solid black",
    // padding: "50px 0 0 0", // padding is not good
    // textAlign : "center"; // but for the vertical that's possible ?
    width: "100px",
    height: "100px"
  };
  return (
    <div className="App">
      <div style={style}>milieu</div>
    </div>
  );
}

简洁解决方案:使用Flexbox

直接修改容器样式,添加Flex布局属性,就能同时实现水平+垂直居中,既不改变容器尺寸,也不需要额外嵌套元素:

const style = {
  border: "1px solid black",
  width: "100px",
  height: "100px",
  display: "flex",
  alignItems: "center", // 实现垂直居中
  justifyContent: "center" // 实现水平居中
};

这是目前最推荐的方案,代码简洁逻辑清晰,现代浏览器都完美支持,不会引入额外复杂度。

更简洁的Grid方案(可选)

如果偏好更短的代码,也可以用Grid布局,一行属性搞定双居中:

const style = {
  border: "1px solid black",
  width: "100px",
  height: "100px",
  display: "grid",
  placeItems: "center" // 同时设置水平和垂直居中
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:05:19