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

相关推荐
阿豪只会阿巴1 小时前
【没事学点啥】TurboBlog轻量级个人博客项目——项目介绍
javascript·python·django·html
不考研当牛马6 小时前
HTML CSS 新手大全初学者必看 (含有部分 JavaScript)
javascript·css·html
暗不需求7 小时前
告别“class 命名地狱”:从面向对象 CSS 到原子 CSS(Tailwind) 的思维跃迁
前端·css·react.js
2501_906467638 小时前
html5网页中如何实现内网大文件的加密下载?
前端·html·html5·vue上传解决方案·vue断点续传·vue分片上传下载·vue分块上传下载
极客小俊8 小时前
【从零到一】用HTML5+CSS+JavaScript实现一个属于自己的mp3免费音乐播放器 (4) JS交互功能(音乐进度条)
javascript·css·html5·前端开发·免费教程·代码案例·手搓音乐播放器
何何____9 小时前
css变换语法介绍及案例展示
前端·css
gCode Teacher 格码致知11 小时前
Javascript提高:点击飘忽不定的气球,气球爆炸并增加分数-由Deepseek产生
javascript·css·css3
用户0595401744611 小时前
Playwright 多标签页 IndexedDB 同步测试踩坑实录:折磨我6小时的浏览器沙箱陷阱
前端·css
ZC跨境爬虫12 小时前
跟着 MDN 学 HTML day_25:(数字音频概念完全解析)
前端·ui·html·edge浏览器·媒体
Raytheon_code1 天前
从零到一:我用微信小程序做了一款串珠DIY定制工具
css·微信小程序·html5·ai编程