对齐的形式能够以方向来进行划分,横向对齐以及纵向对齐css
横向对齐也就是水平对齐,纵向对齐也就是垂直对齐html
其中讨论最多的是居中方式,一下主要是从横向和纵向两个大方向来总结居中的方式markdown
对于行内元素来讲,水平居中很是简单,直接使用text-align:center
布局
如下是html定义的行内元素flex
<span>
spa
<a>
code
<br>
orm
<b>
htm
<strong>
input
<img>
<sup>
<sub>
<i>
<em>
<del>
<input/>
<textarea>
<select>
使用margin
前提是要给居中的块级元素设定width,不然无效
width:100px; margin: auto 0; 复制代码
使用绝对定位与margin
须要知道居中元素的宽度 ,并且父级元素要设置为相对定位
width: 20px; position: absolute; left: 50%; margin-left: -10px; 复制代码
使用绝对定位和transform
width: 20px; position: absolute; left: 50%; transform: translateX(-50%); 复制代码
使用flex布局
父元素display:flex
子元素align-self:center
使用line-height 须要知道父元素的高度,并把行内元素的line-height设置成相同的值
.father { height: 500px; background-color: antiquewhite; } .father span { line-height: 500px; } 复制代码
一样,块级元素也能够使用line-height进行垂直居中
使用绝对定位,margin
须要设置元素的高度
position: absolute; height: 20px; top: 50%; margin-top: -10px; 复制代码
使用绝对定位,transform
position: absolute; top: 50%; transform: translateY(-50%); 复制代码
使用flex布局
设置容器为flex布局,以下
height: 100px; background: aquamarine; display: flex; align-items: center; 复制代码