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

相关推荐
whatever who cares37 分钟前
CSS3 伪元素(Pseudo-elements)大全
前端·css·css3
积极向上的龙1 小时前
首屏优化,webpack插件用于给html中js自动添加异步加载属性
javascript·webpack·html
程序员Bears2 小时前
从零打造个人博客静态页面与TodoList应用:前端开发实战指南
java·javascript·css·html5
清风细雨_林木木3 小时前
Vue 2 项目中配置 Tailwind CSS 和 Font Awesome 的最佳实践
前端·css·vue.js
逊嘘3 小时前
【Web前端开发】CSS基础
前端·css
小宁爱Python3 小时前
深入掌握CSS Flex布局:从原理到实战
前端·javascript·css
影子信息4 小时前
css 点击后改变样式
前端·css
小堃学编程5 小时前
前端学习(1)—— 使用HTML编写一个简单的个人简历展示页面
前端·javascript·html
前端小巷子6 小时前
CSS3 遮罩
前端·css·面试·css3
Samuel-Gyx7 小时前
前端 CSS 样式书写与选择器 基础知识
前端·css