首页 > Web开发 > 详细

css学习笔记之盒子居中

时间:2016-04-19 06:04:32      阅读:120      评论:0      收藏:0      [点我收藏+]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>盒子居中</title>
<style>
#box1{
	width:200px;
	height:200px;
	padding:100px;
	border:1px solid black;
	position:absolute;
	top:50%;
	left:50%;
	margin-top:-201px;
	margin-left:-201px;
	
	}
h1{
	text-align:center;}

</style>
</head>
<body>
<div id="box1">
<h1>我要居中</h1>
</div>
</body>
</html>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#box1{
    width:200px;
    height:200px;
    padding:100px;
    border:1px solid black;
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    
    
    }
h1{
    text-align:center;}

</style>
</head>
<body>
<div id="box1">
<h1>我要居中</h1>
</div>
</body>
</html>

这两种方法都是让一个盒子在浏览器窗口居中。

第一种方法:先设置绝对定位,top和left的值都设置为50%。再把盒子的margin-top设置为盒子高度的一半,margin-left设置为盒子宽度的一半即可(注意这里的值都是负的)。

第二种方法:也是通过绝对定位,不过这里把top,right,left,bottom的值都设置为0,再设置marign:auto。盒子自然而然就居中了。

 

css学习笔记之盒子居中

原文:http://www.cnblogs.com/rareearth/p/5406473.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!