定宽高元素
公共文档结构及样式
1 2 3
| <div class="parent"> <div class="child">test</div> </div>
|
1 2 3 4 5 6 7 8 9 10
| .parent { width: 600px; height: 250px; border: 1px solid black; } .child { height: 100px; width: 100px; background: gray; }
|
绝对定位 + 负边距
设置top
和left
属性为 50%,同时将外边距设置为负的宽高值的一半
1 2 3 4 5 6 7 8 9 10
| .parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; }
|
绝对定位 + auto
将各个方向的距离设置为 0,然后将外边距设置为auto
1 2 3 4 5 6 7 8 9 10 11
| .parent { position: relative; } .child { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; }
|
绝对定位 + calc
可以通过计算属性计算出左边和上边的距离
1 2 3 4 5 6 7 8
| .parent { position: relative; } .child { position: absolute; top: calc(50% - 50px); left: calc(50% - 50px); }
|
不定宽高元素
公共文档结构及样式
1 2 3
| <div class="parent"> <div class="child">TEST</div> </div>
|
1 2 3 4 5 6 7 8 9
| .parent { width: 600px; height: 250px; border: 1px solid black; font-size: 2em; } .child { background: lightgray; }
|
transform
的translate
可以设置为百分比,相对于自身的宽高
1 2 3 4 5 6 7 8 9
| .parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
|
设置为行内元素
将子元素通过text-align
和vertical-align
分别调整为水平居中和垂直居中
1 2 3 4 5 6 7 8 9 10 11 12
| .parent { line-height: 250px; text-align: center; font-size: 0px; } .child { display: inline-block; vertical-align: middle; line-height: initial; text-align: left; font-size: 24px; }
|
需要在子元素中重新调整文字效果
table-cell
通过设置table-cell
可以使普通元素具有 table 的效果
1 2 3 4 5 6 7 8
| .parent { display: table-cell; text-align: center; vertical-align: middle; } .child { display: inline-block; }
|
伪元素
vertical-align
属性定义行内元素的基线相对于该元素所在行的基线的垂直对齐方式
可以设置一个宽度为 0 且不显示的伪元素,高度为 100%,是所在行的基准元素;利用vertical-align: middle
将父元素的基线设置为伪元素的中线,然后其他行内元素采用中线对齐时,就会要对齐伪元素的中线。而伪元素的高度为 100%,所以它的中线就是整个父元素的中线
1 2 3 4 5 6 7 8 9 10 11 12 13
| .parent { text-align: center; } .parent::before { content: ''; display: inline-block; vertical-align: middle; height: 100%; } .child { display: inline-block; vertical-align: middle; }
|
参考 https://juejin.im/post/5b24df0ce51d4558b64f0880#heading-4
flex
1 2 3 4 5
| .parent { display: flex; justify-content: center; align-items: center; }
|