div 固定宽高 水平垂直居中方法

    div固定宽高,水平垂直居中,根据所用单位不一样,分红两种状况,分别是“px”和“%”状况。css

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

       

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

       只须要用绝对定位到屏幕中间,而后利用margin-left和margin-top取值就能够实现。spa

 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结构不变。code

<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>
相关文章
相关标签/搜索