1、行内元素水平居中,可以在父元素中使用text-align:center;垂直居中可以用,line-height:100px;例如:
代码语言:javascript代码运行次数:0运行复制
div{
width:300px;
height:100px;
text-align:center;
line-height:100px;
}
文字居中
2、块级元素水平居中,可以用margin:auto;代码如下:
代码语言:javascript代码运行次数:0运行复制
div{
width:300px;
height:100px;
margin:0px auto;//上下边距为0,水平居中
background:#ccc;
}
文字居中
3、元素绝对居中,利用定位position,代码如下:
代码语言:javascript代码运行次数:0运行复制
div{
width:300px;
height:100px;
position:relative;
}
div p{
width:100px;
height:20px;
position:absolute;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
}
文字居中
4、元素绝对居中的另一种方法,代码如下:
代码语言:javascript代码运行次数:0运行复制
div{
width:300px;
height:100px;
position:relative;
background:#bbb;
}
div p{
width:100px;
height:20px;
position:absolute;
top:50%;
margin-top:-10px;
left:50%;
margin-left:-50px;
}
文字居中