首页 > 技术文章 > div 固定宽高 水平垂直居中方法

lovemomo 2016-11-18 14:28 原文

    div固定宽高,水平垂直居中,根据所用单位不同,分成两种情况,分别是“px”和“%”情况。

    例:将三层div做出三个边框,要求水平垂直居中。效果如图

       

  • 情况一(单位是px时):

       只需要用绝对定位到屏幕中间,然后利用margin-left和margin-top取值就可以实现。

 1 <style type="text/css">
 2 
 3 .a {
 4     border: 1px solid #00caca;
 5      width: 900px;
 6     height: 500px; 
 7     position: absolute;
 8     top: 50%;
 9     left: 50%;
10     margin-left: -450px;
11      margin-top: -250px;
12 
13     display: flex;   //flex让内部div水平垂直居中
14     flex-direction: row;
15     justify-content: center;
16     align-items: center; 
17 }
18  .b {
19     border: 1px solid #00cacc;
20     width: 80%;
21     height: 70%;
22     display: flex;
23     flex-direction: row;
24     justify-content: center;
25     align-items: center;
26 }
27 .c {
28     border: 1px solid #00fffb;
29     width: 60%;
30     height: 60%;
31 }
<body>
    <div class="a">
        <div class="b">
            <div class="c">ssssss</div>
        </div>
    </div>
</body>
  • 情况二(单位是%):

      由于%是基于父元素宽高,采用margin-left值为负本身宽高一半失效,因此,需要计算定位top 和 left值,使其居中。代码如下,其中,HTML结构不变。

<style type="text/css">
body {
    width: 100%;     //需要给body设置宽高
    height: 100%;
} 
.a {
    border: 1px solid #00caca;
     width: 80%;
    height: 80%; 
    position: absolute;
    top: 10%;    //根据自身宽高占body的80%,推算定位top值
    left: 10%;    //同上
     margin-left: 0;
     margin-top: 0; 

    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center; 
}
 .b {
    border: 1px solid #00cacc;
    width: 80%;
    height: 70%;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}
.c {
    border: 1px solid #00fffb;
    width: 60%;
    height: 60%;
} 
</style>

 

推荐阅读