垂直水平居中总结css

水平居中:给div设置一个宽度,然后添加margin:0 auto属性

div{
   width:200px;
   margin:0 auto;
 }

让绝对定位的div垂直水平居中一(大盒子设置个相对定位)

div {
   position: absolute;
   width: 300px;
   height: 300px;
   margin: auto;
   top:0;
   left: 0;
   bottom: 0;
   right: 0;
   background-color: pink; /* 方便看效果 */
}


垂直水平居中二
父元素相对定位
子元素绝对定位居上和居左50%然后减去自身宽度的距离就可以实现

<div class="box">

<div class="centent"></div>

</div>

 

.box {

  position: relative;

  width: 800px;

  height: 800px;

  background-color: red;

 }

.centent {

   position: absolute;     /* 相对定位或绝对定位均可*/

   width:500px;

   height:300px;

   top: 50%;

   left: 50%;

   margin: -150px 0 0 -250px;      /*外边距为自身宽高的一半 */

   background-color: pink;     /* 方便看效果 */

 } 

 

垂直水平居中三
利用 flex 布局

<div class="box">
  <div class="content"><div>
</div>
.box {
   display: flex; align-items: center; /* 垂直居中 */ justify-content: center; /* 水平居中 */
  width:300px;
  height:300px;
  background-color:red;
}
.content {
  width:100px;
  height:100px;
  background-color:pink;
}
此文仅是为了自己学习记录笔记总结

posted @ 2018-08-24 15:50  vaelcy  阅读(150)  评论(0)    收藏  举报