当前位置:   article > 正文

css中通过定位和弹性布局设置垂直居中的方法_弹性定位居中

弹性定位居中

方式一:绝对定位方式且已知宽高

position:absolute;
top:50%;
left:50%;
margin-top:-3em;
margin-left:-7em;
width:14em;
height:6em;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

方式二:绝对定位+未知宽高+translate

position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
//需要补充浏览器前缀
  • 1
  • 2
  • 3
  • 4
  • 5

方式三:flex轻松搞定水平垂直居中(未知宽高)

display:flex;
align-items:center;//使内部元素垂直居中
justify-content:center;//使内部元素水平居中
  • 1
  • 2
  • 3

例:

<style>
  .box{
    width: 400px;
    height: 400px;
    border: 1px solid orange;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .item{
    width: 100px;
    height: 200px;
    background-color: orangered;
  }
</style>
<body>
  <div class="box">
    <div class="item"></div>
  </div>
</body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

运行图:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/702766
推荐阅读
相关标签
  

闽ICP备14008679号