还是用css的position属性,如下的html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<style type="text/css">
.div1{ width: 100px; height: 100px; border: 1px solid #000000;}
.div2{ width:40px ; height: 40px; background-color: green;}
.div11{
position: relative;
}
.div22{
position: absolute;margin:auto; top: 0;left: 0;right: 0;bottom: 0;
}
</style>
<div class="div1 div11">
<div class="div2 div22">
</div>
</div>
</body>
</html>
四、方法四
利用css3的新增属性table-cell
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<style type="text/css">
.div1{ width: 100px; height: 100px; border: 1px solid #000000;}
.div2{ width:40px ; height: 40px; background-color: green;}
.div11{
display: table-cell;vertical-align: middle;
}
.div22{
margin: auto;
}
</style>
<div class="div1 div11">
<div class="div2 div22">
</div>
</div>
</body>
</html>
这个方法还有一个好处就是,div2的高度可以不固定,如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<style type="text/css">
.div1{ width: 100px; height: 100px; border: 1px solid #000000;}
.div2{ width:40px ; background-color: green;}
.div11{
display: table-cell;vertical-align: middle;
}
.div22{
margin: auto;
}
</style>
<div class="div1 div11">
<div class="div2 div22">
div居中方法
</div>
</div>
</body>
</html>
总结
以上所述是小编给大家介绍的CSS实现DIV居中的三种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对软件开发网网站的支持!










