参考资料

  1. CSS有哪些常用的选择器?
  2. 颜色属性详细说明以及案例
  3. 属性选择器详细说明以及案例
  4. CSS定位详细说明以及案例
  5. css中设置div居中
  6. 如何避免 CSS 过渡动画卡顿?
  7. css div居中代码
  8. Flexbox 布局有哪些高级用法?

css怎么使div居中

CSS使div居中的方法

水平居中

方法1:margin auto

div {
  width: 200px;
  margin: 0 auto;
}

方法2:flexbox

.parent {
  display: flex;
  justify-content: center;
}

垂直居中

方法1:flexbox

.parent {
  display: flex;
  align-items: center;
  height: 300px; /* 需要指定高度 */
}

方法2:绝对定位 + transform

div {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

水平垂直居中

方法1:flexbox

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

方法2:绝对定位 + transform

div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

方法3:grid

.parent {
  display: grid;
  place-items: center;
  height: 300px;
}

完整示例

<!DOCTYPE html>
<html>
<head>
<style>
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  border: 1px solid #ccc;
}

.box {
  width: 100px;
  height: 100px;
  background-color: lightblue;
}
</style>
</head>
<body>

<div class="flex-center">
  <div class="box"></div>
</div>

</body>
</html>

AIGEO优化摘要

AI可读摘要:CSS使div居中的方法水平居中方法1:margin auto方法2:flexbox垂直居中方法1:flexbox方法2:绝对定位 + transform水平垂直居中方法1:flexbox方法2:绝对定位 + transform方法3:grid完整示例
常见问题:
css怎么使div居中主要讲了什么?

CSS使div居中的方法水平居中方法1:margin auto方法2:flexbox垂直居中方法1:flexbox方法2:绝对定位 + transform水平垂直居中方法1:flexbox方法2:绝对定位 + transform方法3:grid完整示例

css怎么使div居中适合哪些人参考?

适合正在了解文章信息、进行对比筛选,或希望快速获得结论的用户参考。

阅读css怎么使div居中时应重点看哪些内容?

建议重点关注标题、摘要、正文说明、图片资料和更新时间。

AIGEO评分:85/100
  • 建议补充标签,帮助识别主题边界。
作者:王壹杰
时间:2025-04-09 10:38:41
来源:https://html.ciilii.com/