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;这三个需要一起用

相关推荐
疯狂的沙粒11 分钟前
在web-view 加载的本地及远程HTML中调用uniapp的API及网页和vue页面是如何通讯的?
前端·uni-app·html
小妖66615 分钟前
html 滚动条滚动过快会留下边框线
前端·html
CodeBlossom8 小时前
javaweb -html -CSS
前端·javascript·html
鱼馅饼11 小时前
vscode使用系列之快速生成html模板
ide·vscode·html
然我15 小时前
JavaScript的OOP独特之道:从原型继承到class语法
前端·javascript·html
木木夕酱15 小时前
前端响应式网站编写套路
css·react.js
用户268348422395916 小时前
前端换肤功能最佳实践:从基础实现到高级优化
前端·css
冷凌爱16 小时前
总结HTML中的文本标签
前端·笔记·html
灏瀚星空18 小时前
用HTML5 Canvas打造交互式心形粒子动画:从基础到优化实战
前端·html·html5
蓝婷儿19 小时前
第二章支线八 ·CSS终式:Tailwind与原子风暴
前端·css