<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>填充</title>
<style type="text/css">
#box1{
width:100px;
height:100px;
padding:10px;
border:1px solid red;
text-align:center;
}
</style>
</head>
<body>
<div id="box1">盒子1</div>
</body>
</html>
有时候,我们会想让文字在某个盒子中垂直居中,这个时候我们可以使用line-height属性。可以给文字外面加个span标签,然后给span添加line-height属性,值为外面盒子的高度,line-height是行高,即文字相对于这个高度垂直居中。如果有背景图或者小icon一般加在span标签上。
例如:
<div class="outer">
< span>测试的文字</span>
</div>
.outer {
height:100px;
}
.outer span {
line-height:100px;
}
这样文字就能在这个高100px的盒子中居中了。有时候可能会需要对span设置display:inline-block,不行的时候可以试一下
最简单方法:
父元素高度确定的单行文本的竖直居中的方法是通过设置父元素的 height 和 line-height 高度一致来实现的。
#box1{
width:100px;
height:100px;
line-height:100px;
padding:10px;
border:1px solid red;
text-align:center;
}text-align:center;
是水平居中对齐
正确代码,参考:
http://www.w3school.com.cn/cssref/pr_box-align.asp
http://www.w3school.com.cn/tiy/t.asp?f=css3_box-pack
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>填充</title>
<style type="text/css">
#box1{
width:100px;
height:100px;
padding:10px;
border:1px solid red;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Chrome, and Opera */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
}
</style>
</head>
<body>
<div id="box1">盒子1</div>
</body>
</html>