水平居中
1. inline和inline-*元素水平居中:text-align:center
2. block元素水平居中:
block定宽:margin-left: auto; margin-right; auto;
block不定宽:
3. fit-content和margin auto居中(可实现容器宽度随内容增多而自动增大)
.box{ width: -moz-fit-content; width: -webkit-fit-content; width:fit-content; margin:0 auto; }
4. 左右拉伸和margin auto居中(定宽度的absolute元素水平居中)
.box{ position:absolute; left:0; right:0; margin:0 auto; width: 300px; }
垂直居中
1. 父元素高度不定
(inline,inlie-*,block)垂直居中: 父元素上下内边距相等 padding-top = padding-bottom
替换元素(img,input,textarea,object,video,audio,canvas等):object-position: center
2. 父元素高度确定
inline和inline-*竖直居中
单行文本竖直居中: line-height与父元素高度相同
多行文本等其他竖直居中: (模拟td)display:table-cell;vertical-align:middle;
block竖直居中:
a. block定高: position: absolute; top: 50%; margin-top: -height/2
b. block不定高:
<1. (模拟td)display:table-cell;vertical-align:middle;
<2. (模拟table) 父容器display:table, 子容器display:table-cell
.parent {display: table;} .child { display: table-cell; vertical-align: middle; }
<3. transform方法:position: releative或者absolute; top: 50%; transform: translateY(-50%)
3. 上下拉伸和margin auto居中(定高度的absolute元素垂直居中)
.box{ position:absolute; top:0; bottom:0; margin:auto 0; height: 300px; }
4. 伪元素撑开对齐
.parent{ font-size:0;//消除inline-block水平空隙 } .son,.parent:after{ display:inline-block; vertical-align:middle; font-size:24px;//修正字体 } .parent:after{ content:''; height:100%; }
5. writing-mode配合text-align或margin:0 auto实现垂直居中
.verticle-mode { writing-mode: tb-lr; writing-mode: vertical-lr; -webkit-writing-mode: vertical-rl; } .horizontal-mode{ writing-mode: lr-tb; writing-mode: horizontal-tb; -webkit-writing-mode: horizontal-rl; }
<div class="item"> <span class="item-left">1. </span> <span class="item-right">标题</span> </div>
.item{ height:60px;background-color:lightcoral;border-radius: 8px;padding:5px 10px;line-height: 30px; writing-mode: tb-lr; -webkit-writing-mode: vertical-lr; writing-mode: vertical-lr; text-align: center; } .item *{ writing-mode: lr-tb; writing-mode: horizontal-tb; }
6. relative垂直居中
元素relative,top: 50%, margin-top: -height/2,或者 transform: translateY(-50%),可垂直居中,
水平垂直居中
1. absolute元素水平居中(缺点:元素中内容很长,会导致超出内容不可见)
.center_middle{ position:absolute; left:0; top:0; right:0; bottom:0; margin:auto; width: 800px; height: 600px; }
2. flex
flex正统
.parent { display: flex; align-items: center; justify-content: center; }
flex + margin:auto
.parent { display: flex; margin: 0; >.child { margin: auto; } }