div嵌套div,我们经常都用。布局是基础,扎实的基础会让你在解决问题的时候更柔韵有余。这是我出来工作之后深深的领悟。下面是我对外层布局的一些小总结。
<!DOCTYPE HTML>
<html>
<head>
<title>div嵌套div居中问题</title>
<meta http-equiv="content-type"content="text/html; charset=UTF-8"/>
<style type="text/css">
.BD-one{
width:200px;
height:200px;
background-color:red;
}
.content-one{
width:40px;
height:40px;
background-color:yellow;
margin:0 auto; /* 这是最经常用到的 */
}
.BD-two{
width:200px;
height:200px;
background-color:green;
/* 这里的 父容器需要有position的设置,无论是relative 还是 absolute */
position:relative;
}
.content-two{
width:60px;
height:40px;
background-color:yellow;
position:absolute;
/* 这里的 top left:50%都是相对于父容器的 */
top:50%;
left:50%;
/* 这里的 margin-top margin-left:-20px都是相对于自己的。设置不同的值查看效果 */
margin-top:-20px; /* 40/20 */
margin-left:-30px; /* 60/20 */
}
.BD-three{
/* 最外层 用百分比 就不行了 */
/* 如这里width:100%; height:100% */
width:900px;
height:300px;
background-color:blue;
}
.BFB{
/* 父容器用%也是可以的 */
width:20%;
height:20%;
background-color:red;
/* 这里的 父容器需要有position的设置,无论是relative 还是 absolute */
position:relative;
}
.content-three{
width:40px;
height:40px;
background-color:yellow;
position:absolute;
/* 这里的 top left:50%都是相对于父容器的 */
top:50%;
left:50%;
/* 这里的 margin-top margin-left:-20px都是相对于自己的 */
margin-top:-20px;
margin-left:-20px;
</style>
</head>
<body>
<span>这里针对的是静态的HTML元素</span>
<span>如果是动态生成的元素,JS会更好</span>
<span>左右居中</span>
<div class="BD-one">
<div class="content-one"></div>
</div>
<br/>
<span>上下左右居中</span>
<div class="BD-two">
<div class="content-two"></div>
</div>
<span>上下左右居中,父容器采用%的情况</span>
<div class="BD-three">
<div class="BFB">
<div class="content-three"></div>
</div>
</div>
</body>
</html>
才疏学浅,如有建议或者意见,望留言指正。
(●'◡'●)