一:让div水平居中的css方法:(默认情况下div的display为block,以下是针对display:block来说的)
1、给要设置水平居中的div设置display:block ,margin:0 auto,width , height4个属性,可以让块级元素水平居中(默认情况下,div的position:static)
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<style>
div{
width:200px;
height:200px;
background-color:red;
display: block;
margin:0 auto;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
显示的效果:
2、给要水平居中的div设置属性:width height position left margin-left
其中left:50% position:的值除了static之外的都可以 marin-left:的值为负数,数值大小为width的一半
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<style>
div{
position:relative;
left:50%;
width:400px;
height:400px;
margin-left:-200px;
background-color:red;
display: block;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
二、让div竖直居中的css方法:(默认情况下div的display为block,以下是针对display:block来说的)
1、给要竖直居中的div设置属性:width height position top margin-top
top:50% margin-top:为负值,值大小为height的一半 position为absolute或者fixed
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<style>
div{
position: absolute;
top: 50%;
width: 400px;
height: 500px;
margin-top: -250px;
background-color: red;
display: block;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
三、让div同时水平竖直居中的方法
1、同时水平竖直居中的div设置属性:width height position top margin-top left margin-left
top:50% left:50% position:absolute/fixed margin-top:-height/2 margin-left:-width/2
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<style>
div{
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: 500px;
margin-top: -250px;
margin-left: -200px;
background-color: red;
display: block;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
原文地址:https://blog.csdn.net/tangxiujiang
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。