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

相关推荐
Hacker_Z&Q7 小时前
CSS 笔记2 (属性)
前端·css·笔记
计算机程序设计小李同学9 小时前
幼儿园信息管理系统的设计与实现
前端·bootstrap·html·毕业设计
tao35566710 小时前
【用AI学前端】HTML-02-HTML 常用标签(基础)
前端·html
2601_9495328410 小时前
Psello HTML Template: A Developer‘s Deep-Dive Review and Guide - Download Free
前端·windows·html·seo·wordpress·gpl
CappuccinoRose10 小时前
CSS前端布局总指南
前端·css·学习·布局·flex布局·grid布局·float布局
穿过锁扣的风10 小时前
如何操作HTML网页
前端·javascript·html
txwtech12 小时前
第20篇esp32s3小智设置横屏
前端·html
life码农13 小时前
HTML文本换行显示几种方法总结
前端·html
强子感冒了13 小时前
CSS基础学习:CSS选择器与优先级规则
前端·css·学习
啟明起鸣13 小时前
【Nginx 网关开发】上手 Nginx,简简单单启动一个静态 html 页面
运维·c语言·前端·nginx·html