didiv合作发<style> *{ margin: 0; padding: 0; } .outer{ margin: 0 auto; width: 80%;灌灌灌

来源:互联网 发布:pi开关电源设计软件 编辑:程序博客网 时间:2024/05/17 23:11

div在另一个div中垂直水平居中的方法:

(1)传统定位法

该方法采用子绝父相的定位:给top:50%;left:50%;使子盒子的左上方的点到达父盒子的中心点;然后使用:

(1.1)

通过margin来让子盒子移动;使其中心点移动到与父盒子中心点重合;来达到目的。

CSS:

<style>
*{
margin: 0 auto;
}
.outer{
width: 80%;
height: 400px;
background-color: gray;
position: relative;
}
.inner{
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>

HTML:

<div class="outer">
<div class='inner'>2</div>
</div>

(1.2)

与方法一类似,只不过使用了css3的transform来进行移动

CSS:

<style>
*{
margin: 0;
padding: 0;
}
.outer{
margin: 0 auto;
width: 80%;
height: 400px;
background-color: yellow;
position: relative;
}
.inner{
width: 80%;
height: 100px;
background-color: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)


}
</style>

(2)绝对定位法

使用:top:0;left:0;rigth:0;bottom:0;  =====>margin:auto;

css:

<style>
*{
margin: 0;
padding: 0;
}
.outer{
width: 80%;
height: 400px;
background-color: gray;
position: relative;
}
.inner{
width: 50%;
height: 50%;
background-color: red;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>

(3)弹性盒布局

<style>
*{
margin: 0;
padding: 0;
}
.outer{
margin: 0 auto;
width: 80%;
height: 400px;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
}
.inner{
height: 50%;
background-color: red;


}
</style>

原创粉丝点击