未知宽高元素怎么上下左右垂直居中

1.position+transform

position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);

 

2.flex

display: flex;
align-items: center;
justify-content: center;

  

3.table-cell

<div class="pagination">
    <p>多行居中</p>
</div>
<style>
.pagination {
  position: relative;
  width:200px;
  height:200px;
  border:1px solid red;
  display: table;
}
.pagination p{
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
</style>

  

4.absolute+margin

position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;

如:

<div class="pagination">
    <p>不等高度的居中不等高度的居中不等高度的居中不等高</p>
</div>
<style>
html,body{width:100%;height:100}
.pagination {
  width:200px;
  height:200px;
  border:1px solid red;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
.pagination p{
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
</style>

  

5.浮动方案  absolute + relative 扩展性强,兼容性强;

<div class="pagination">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
</div>
<style>
.pagination {
  position: relative;
}
.pagination ul {
  position: absolute;
  left: 50%;
}
.pagination li {
  float: left;
  position: relative;/*注意,这里不能是absolute*/
  right: 50%;
}
</style>

  

 

posted @ 2018-03-29 16:52  AlanTao  阅读(849)  评论(0编辑  收藏  举报