html 如何让div居中 html怎么让div标签本身居中
html\u600e\u4e48\u8ba9div\u91cc\u9762\u7684\u5185\u5bb9\u5c45\u4e2d\u663e\u793a\u770b\u4f60\u662f\u4ec0\u4e48\u5185\u5bb9\uff0c\uff0c\u5982\u679c\u662f\u6587\u5b57\uff0c
\u8fd9\u91cc\u7684\u6587\u5b57\u662f\u4f1a\u5782\u76f4\u5c45\u4e2d\u7684
\u5982\u679c\u662f\u5b50\u5143\u7d20\uff0c\uff0c\u53ef\u4ee5\u7ed9\u5b83\u505a\u5b9a\u4f4d\u3002
\u4e2d\u95f4\u8fd9\u4e2adiv\u4e5f\u662f\u5c45\u4e2d\u7684
\u5982\u679c\u662f\u9700\u8981DIV\u5728\u9875\u9762\u6216\u6240\u5728\u7684\u7236\u7ea7\u5bb9\u5668\u4e2d\u5c45\u4e2d\uff0c\u4f60\u53ef\u4ee5\u53c2\u8003\u5c1d\u8bd5\u4ee5\u4e0b\u4ee3\u7801
.a {width:200px;height:150px;background:#333;margin:20px auto; //\u6c34\u5e73\u5916\u8fb9\u8ddd\u81ea\u52a8\uff0c\u8fbe\u5230\u5c45\u4e2d\u76ee\u7684
div居中可以用外边距margin属性来实现。
1、新建html文档,在body标签中添加div标签,标签的id为“header”,这时因为div标签中没有内容且没有设置样式,所以网页中显示空白:
2、这时为div标签设置原题中的css样式,此时虽然div盒子显示了,但是没有居中:
3、此时为div添加一个“margin: 0 auto”属性就会居中显示,“margin”指的是div标签的外边距,“0”指的是div标签上下的外边距,“auto”指的是div标签左右的外边距,并且会根据浏览器窗口大小自动居中,这时就是完整的html和css代码:
DIV居中提供两个方法:
1、简单快捷方法就是加<center>内容</center>标签。
示例:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>center居中</title>
</head>
<body>
<center>
<div>我要居中啦</div>
</center>
</body>
</html>
2、div中加入margin:0 auto属性;自动调节居中。
示例2:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>margin居中</title>
<style type="text/css">
.d1{
border:1px solid red;
width:200px;
height:200px;
text-align:center;
line-height:40px;
margin:0 auto;
}
</style>
</head>
<body>
<div class="d1">
我是div,我居中啦...
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
height: 650px;
}
#header{
position: relative;
width: 778px;
height: 250px;
border: 1px solid red;
background-color: #999;
margin: 0 auto;
top:50%;
margin-top:-125px;
}
</style>
</head>
<body>
<div id="header">
</div>
</body>
</html>
水平居中 margin: 0 auto;
垂直居中 需要给父级设置高度 这里是body
position: relative;
top:50%;
margin-top:-125px;
这是控制垂直居中的代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
html,body{ margin:0px; padding:0px;}
.header{ width:778px; height:250px; background-color:#999999; border:1px solid red; position:absolute; top:0px; right:0px; bottom:0px; left:0px; margin:auto;}
</style>
</head>
<body>
<div id="header" class="header">
</div>
</body>
</html>
以上是我比较常用的方法,不论header宽高如何变化,都会居中,还有一些别的方法,见http://tieba.baidu.com/p/2743929001
<style type="text/css">
#header{width:778px; height:250px; margin:10px auto; text-align:center; background-color:pink;}
/*对于定宽的div,可以用margin:0px auto进行div整体居中,text-align:center;用于在div内的文本居中*/
</style>
<div id="header">
abc<br />
defabcdea<br />
This is a book.
</div>
扩展阅读:html网页div整体居中 ... html div文字上下居中 ... css height auto 如何居中 ... css div高度自适应 ... html div上下居中代码 ... css怎么让div居中靠左 ... css display flex居中 ... html怎么让div可以移动 ... html中怎么让div格子居中 ...