跳至内容
水平居中
- 行内元素,父元素设置text-align: center即可
- 块级元素,元素设置margin: 0 auto即可
- float的元素需要水平居中时,包裹一层width: fit-content的父元素,然后父元素margin: 0 auto携带float元素整体居中
- flex元素在容器中水平居中时,容器设置justify-content: center(flex-direction: row)或者align-items: center(flex-direction: column)即可
- position: absolute; left: 50%; transform: translate(-50%, 0);
- position: absolute; left: 50%; width:已知值; margin-left: -0.5*width已知值;
- position: absolute; left: 0; right: 0; margin: 0 auto;
垂直居中
- 行内元素,设置line-height和父元素高度相同即可
- 行内块元素,设置vertical-align:middle,同时给父元素增加一个content: “”; vertical-align: middle; display: inline-block;height:100%; 的伪元素(::after)即可
- 容器元素设置display: flex; align-items: center;(flex-direction: row)或者justify-content: center(flex-direction: column)即可
- position: absolute; top: 50%; transform: translate(0, -50%);
- position: absolute; top: 50%; height:已知值; margin-top: -0.5*height已知值;
- position: absolute; top: 0; bottom: 0; margin: auto 0;
position: absolute; top: 0; bottom: 0; margin: auto 0; 需要元素(不管是行内、行内块、块级)设置height值才能看出效果,否则height填充满父元素内容区,看不出来居中效果。
position: absolute; top: 0; bottom: 0;会使行内元素铺满父元素垂直区域。
position: absolute; 如果行内元素设置了绝对定位和固定定位,那么height,width设置值也有效果,因为display变成了block。
行内元素,设置line-height和父元素高度相同即可垂直居中(上半行距+文字+下半行距=line-height)