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

相关推荐
佛山个人技术开发6 小时前
个人建站接单|汽车汽配行业宽屏自适应官网模板 工厂企业定制建站源码
前端·css·前端框架·html·汽车·php
古怪今人9 小时前
[前端]HTML盒模型与尺寸,标准文档流,块级元素、内联元素和行内块,CSS选择器
前端·css
AIkk8611 小时前
班级群学习资料分享指南:工具推荐与实践
大数据·人工智能·html
加点油。。。。11 小时前
【1.Obsidian渲染html文件】
前端·html·obsidian
希冀12312 小时前
【CSS学习第八篇】
css·学习·tensorflow
程序员小羊!12 小时前
02CSS预备知识
前端·css3
用户0595401744612 小时前
用LangChain+Chroma实现RAG多轮对话记忆与自动化测试,把bug发现时间从2小时压缩到5分钟
前端·css
用户0595401744613 小时前
我把RAG对话记忆测试从手工用例改成ChromaDB自动化评估,Bug发现率翻了4倍
前端·css
程序员小羊!14 小时前
01HTML预备知识
前端·html
a1117761 天前
粒子化系统(3D-Particles)THreeJS react
前端·html·jetson