父级div宽高不固定,自己div垂直水平居中

"Hello World, Hello Blog"

Posted by wudimingwo on December 15, 2018

html

1
2
3
<div class="box">
         <div class="item"></div>
 </div>

版本1.0 : 定位+margin

css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.box{
        	  position: relative;
        	  top: 0;
        	  left: 0;
        	  border: 1px solid black;
        	}
        	.item {
        	  position: absolute;
        	  width: 100px;
        	  height: 100px;
        	  top: 50%;
        	  left: 50%;
        	  margin-left: -50px;
                  /*必须固定自身宽高*/
        	  margin-top: -50px;
        	  border: 1px solid black;
        	}

版本2.0 定位 + translate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.box{
        	  position: relative;
        	  top: 100px;
        	  left: 0;
        	  border: 1px solid black;
        	}
        	.item {
        	  position: absolute;
        	  width: 100px;
        	  height: 100px;
        	  top: 50%;
        	  left: 50%;
        	  transform: translate(-50%,-50%);
                  /*-50%不必固定自身宽高,文字定位可以用这个*/
        	  border: 1px solid black;
        	}

版本3.0 用flex

1
2
3
4
5
6
7
8
9
10
11
12
        	.box{
        	  display: flex;
        	  flex-direction: column;
        	  justify-content: center;
        	  align-items: center;
        	}
                /*无论block,inline都是有效果的*/
        	.item{
        	  width: 100px;
        	  height: 100px;
        	  border: 1px solid black;
        	}

版本1.0 版本2.0 有一个问题: 子元素进行绝对定位时,父级无法自动撑开包裹. 用 position:relative 会撑开父级.目测居中效果是一样的.