CSS 元素居中的各种方式
水平居中
内联元素
- 外层添加一个块级父元素,并设置
text-align: center;
<div style="text-align: center;">
<a> 内联元素 </a>
</div>
块级元素
- 设置
margin: 0 auto;
以及宽度
<div style="margin: 0 auto; width: 200px;">
块级元素
</div>
多个块级元素
- 方法一 内联
- 外层添加一个块级父元素,并设置
text-align: center;
- 子元素设置成内联元素
- 方法二 flexbox
- 外层添加一个块级父元素,并设置
display: flex; justify-content: center;
relative + absolute
- 父元素
postion: relative;
- 子元素 宽度+偏移量+外边距
- (
width: 500px; left: 50%; margin-left: -250px;
)
垂直居中
内联元素
- 方法一 内边距
- 设置
padding: 50px;
- 方法二 元素高度=行高
- 设置
height:100px; line-height:100px;
- 方法三 flexbox(父元素要设置高度)
- 设置
height:200px; display:flex; flex-direction: column; justify-content: center;
块级元素
宽度、高度固定 width: 18em; height: 10em;
- 方法一
- 父元素设置
position:relative;
- 子元素设置 top和left 为 50%; margin上为一半高 margin左为一半宽
position:absolute; top: 50%; left: 50%; margin-left: -9rem; margin-top: -5rem;
- 方法二
- 父元素设置
position:relative;
- 子元素设置 top 为 calc(50% 剪 一半高) left 为 calc(50% 剪 一半宽)
position:absolute; top: calc(50% - 5em); left: calc(50% - 9em);
宽度、高度不固定
- 父元素设置
position:relative;
- 子元素设置 top和left 为 50%; transform: translate(-50%, -50%);
position:absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
flexbox
- 方法一 margin
- 父元素设置
display: flex;
- 子元素设置 宽度 +
margin: auto;
- 方法二
- 父元素设置
display: flex;
- 子元素设置 宽度 +
justify-content: center; align-items: center;