HTML元素居中

⾏内元素⽔平垂直居中 设置⽗级标签。 ⽔平居中: text-align: center 垂直居中: line-height:盒⼦⾼度

⽔平垂直都居中

复制代码
<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      position: relative;
      width: 200px;
      height: 200px;
      border: 1px solid black;
    }

    .child {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 100px;
      height: 100px;
      background-color: blue;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="child"></div>
  </div>
</body>
</html>

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

这三个需要一起用实现居中

绝对定位 + 四个方向 margin: auto

复制代码
<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      position: relative;
      width: 200px;
      height: 200px;
      border: 1px solid black;
    }

    .child {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 100px;
      height: 100px;
      background-color: blue;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="child"></div>
  </div>
</body>
</html>

top: 0;

left: 0;

right: 0;

bottom: 0;

margin: auto;这5个需要一起用

flex 布局

复制代码
<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 200px;
      height: 200px;
      border: 1px solid black;
    }

    .child {
      width: 100px;
      height: 100px;
      background-color: blue;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="child"></div>
  </div>
</body>
</html>

display: flex;

justify-content: center;

align-items: center;这三个需要一起用

table-cell

复制代码
<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      display: table-cell;
      text-align: center;
      vertical-align: middle;
      width: 200px;
      height: 200px;
      border: 1px solid black;
    }

    .child {
      width: 100px;
      height: 100px;
      background-color: blue;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="child"></div>
  </div>
</body>
</html>

display: table-cell;

text-align: center;

vertical-align: middle;这三个需要一起用

相关推荐
前端Hardy5 分钟前
HTML&CSS:卡片式提交框
css·html
前端Hardy8 分钟前
HTML&CSS:超有趣的登录表单
javascript·css·html
背书包的甜瓜18 分钟前
使用sass 实现px转vh或vw,适配适老化时,在设计图字体大小的基础上,增加3px(可配置),
前端·css·sass
我是谁谁32 分钟前
Canvas 高级应用与实战项目<3>
javascript·css·canvas
江城开朗的豌豆44 分钟前
CSS篇:CSS动画实战:如何让一个盒子平滑移动到另一个盒子?
前端·css·面试
harry7591 小时前
Flex-1 布局实现内部滚动条
前端·javascript·css
the_one1 小时前
🚀让动画动起来!用 CSS 延迟变量打造交互式炫酷小球动画
前端·javascript·css
_Le_1 小时前
css 小师系列:为什么 background 渐变可以叠加,而颜色不可以?
前端·css
前端菜鸟日常2 小时前
前端性能优化核弹级方案:CSS分层渲染+Wasm,首屏提速300%!
前端·css·性能优化·wasm
竹苓丿3 小时前
CSS Grid布局:从入门到放弃再到真香
前端·javascript·css