css3元素垂直居中

  <div class="home">
    <div class="title">温馨世界</div>
    <img src="../../assets/images/bg_img.png" alt="" />
  </div>
.home
  position relative
  width: 99.5%;
  height: 700px;
  margin: 5px auto;
  background #fff
  display: -webkit-box;
  -moz-box-align: center;
  -webkit-box-align: center;
  -moz-box-pack: center;
  -webkit-box-pack: center;
  text-align center
  .title
    position absolute
    font-size 36px
    color #31C2A0
  img
    display inline-block
    width 75%

 兼容性

.conter{
    width: 600px; height: 400px;
    position: absolute; left: 50%; top: 50%;
    margin-top: -200px;    /* 高度的一半 */
    margin-left: -300px;    /* 宽度的一半 */
}

transform中translate偏移的百分比值是相对于自身大小的,可以这样实现css绝对定位居中

.conter{
    width: 600px; height: 400px;
    position: absolute; left: 50%; top: 50%;
    transform: translate(-50%, -50%);    /* 50%为自身尺寸的一半 */
}

margin:auto实现绝对定位元素的居中(上下左右均0位置定位;margin: auto)

.conter{
    width: 600px; height: 400px;
    position: absolute; left: 0; top: 0; right: 0; bottom: 0;
    margin: auto;    /* 有了这个就自动居中了 */
}

 

posted @ 2021-04-13 09:57  ronle  阅读(59)  评论(0编辑  收藏  举报