1 行内块居中
设置父元素的 text-align: center
2 块级元素
设置当前块级元素(宽度) margin: 0 auto;
3 绝对定位
元素有宽度的情况下 left0/right0 margin: 0 auto;
4 flex
justify-content: center
1 绝对定位
元素有高度的情况下, top/bottom/margin: auto 0;
2 flex 布局
align-items: center; 变为包含块
3 transfrom
trnaslate(0, -50%)

DOCTYPE html>
<html lang="en">
<head>
<style>
/* position relative 相对 absolute 绝对 fit-content自动调整*/
.container {
position: relative;
height: 300px;
background-color: orange;
}
.container .box1 {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
width: 100px;
/* height: 100px; */
height: fit-content;
background-color: red;
}
style>
head>
<body>
<div class="container">
<div class="box1">box1div>
123
div>
body>
html>

DOCTYPE html>
<html lang="en">
<head>
<style>
.flex-container {
display: flex;
align-items: center;
height: 300px;
background-color: pink;
}
.flex-container .box {
background-color: red;
}
style>
head>
<body>
<div class="flex-container">
<div class="box">123div>
div>
body>
html>

DOCTYPE html>
<html lang="en">
<head>
<style>
.transform-container {
height: 300px;
background-color: orange;
}
.transform-container .box {
display: inline-block;
height: 100px;
background-color: #f00;
/*
1. 让元素向下位移父元素的50%
2. 让元素向上位移自身的50%
*/
/* margin-top: 50%; 的百分比是相对于包含块(父元素)的宽度 */
/* margin-top: 50%; */
position: relative;
top: 50%;
transform: translateY(-50%);
transform: translate(0 ,- 50%);
}
style>
head>
<body>
<div class="transform-container">
<div class="box">coderwhydiv>
123
div>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<style>
body {
display: flex;
height: 100vh;
}
.test {
margin: auto;
background-color: red;
}
style>
head>
<body>
<div class="test">我是水平垂直居中元素div>
body>
html>

DOCTYPE html>
<html lang="en">
<head>
<style>
.test {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: skyblue;
}
style>
head>
<body>
<div class="test">我是水平垂直居中元素div>
body>
html>

DOCTYPE html>
<html lang="en">
<head>
<style>
.test {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: red;
}
style>
head>
<body>
<div class="test">
我是水平垂直居中元素
transform 属性向元素应用 2D 或 3D 转换。该属性允许我们对元素进行旋转、缩放、移动或倾斜。
translate 就是平移是同时设置 translateX 和 translateY。
div>
body>
html>