首先来将常见的块级元素和行内元素进行分类比较:
块级元素
- 总是从新的一行开始;
- 高度宽度可以进行设置(宽度默认为100%);
- 可以包含块级元素和行内元素
- 常见块级元素:
- 标题类,如
<h1> </h1>
- 文本类,如
<p></p>
- 列表,表格,如
<ul></ul>
<li></li>
<dl></dl>
<table></table>
复制代码
<div></div>
行内元素(内联元素)
- 高度,宽度不能设置;
- 不会另起一行,与其他元素在同一行内;
- 不能包含块级元素;
- 常见行内元素:
<span></span>
<img>
<a></a>
<em></em>
<input>
然后再来比较块级元素和行内元素的居中
水平居中
text-align:center;
这个属性规定的是元素中的文本水平居中
<style>
div{
text-align: center;
}
</style>
<div>
<p>css居中</p> //继承div
<span>css居中</span>
</div>
复制代码
上面代码两个都能居中,p元素占整行,但是文本处于居中位置;span元素处于文本位置,所以span元素跟随着文本居中。
margin:0 auto;
只对块级元素起作用。如果需要对行内元素如
<a></a>
<img>
复制代码
等进行水平居中操作,可以用display:block;width:100px; /*一定要设置宽度*/
- 绝对定位
<style type="text/css">
div{
background-color: gray;
position: absolute;
width: 1000px;
left: 50%;
margin-left: -500px;/*左边距是当前块级元素宽度的一半*/
}
</style>
复制代码
绝对定位的这种方法对于宽度已知的块级元素来说非常方便,但如果是行内元素,宽度随内容变化,不容易得到。
- 浮动
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
position: relative; /*这个相对定位不能缺*/
}
ul{
position: relative;
float: left; /*向左浮动*/
left: 50%; /*距离左边一半的父元素宽度*/
}
li{
list-style-type: none;
width: 100px;
float: left; /*向左浮动*/
text-align: center;
background-color: gray;
position: relative; /*相对定位*/
right: 50%; /*距离右边一半的父元素宽度*/
}
</style>
复制代码
这种方法不需要知道父元素宽度具体值就可以用使用,可用于行内元素。
垂直居中
vertical-align:middle;
将元素放在父元素的中部,只对行内元素起作用。- 外边距(margin)自动:将绝对定位的块级元素垂直居中
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.a1{
position: relative;
background-color: black;
width: 400px;
height: 200px;
color: white;
margin-top: 100px;
}
.a2{
position: absolute;/*绝对定位*/
/*left: 0;
right: 0;*/ /*若需要水平居中,可以加这两句*/
top: 0;
bottom: 0;
background-color: white;
width: 40px;
height: 100px;
margin: auto 10px;/*上下自动*/
}
</style>
<div class="a1">
<div class="a2"></div>
</div>
复制代码
- 外边距(margin)通过具体数值垂直居中,适用于块级元素。
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.a1{
position: relative;
background-color: black;
width: 500px;
height: 200px;
}
.a2{
background-color: gray;
position: absolute;
width: 100px;
height: 50px;
top: 50%;
margin-top: -25px;/*上边距是当前块级元素宽度的一半*/
}
</style>
<div class="a1">
<div class="a2"></div>
</div>
复制代码
line-height
设置行高,不允许负值。严格意义上说这个属性是让文本行垂直居中,并不是文字垂直居中。特别适合有文字的列表和导航栏。块级元素也可用。
<style type="text/css">
*{
margin: 0;
padding: 0;
}
ul{
width: 50%;
margin:50px auto;
text-align: center;
background-color: black;
height: 30px;
}
li{
list-style-type: none;
background-color: gray;
float: left;
margin-right: 10px;
line-height: 30px; /*与ul的height相同*/
}
</style>
<body>
<ul>
<li>css</li>
<li>css</li>
<li>css</li>
<li>css</li>
<li>css</li>
</ul>
</body>
复制代码
(持续更新中~) 不正确的地方,恳请指出,谢谢~