如何垂直居中一个元素

2019-03-17  本文已影响0人  nomooo
单行内联元素垂直居中

利用line-height与height相同即可

<div id="box">
     <span>单行内联元素垂直居中。</span>。
</div>
<style>
 #box {
    height: 120px;
    line-height: 120px;
    border: 2px dashed #f69c55;
    }
</style>
多行内联元素垂直居中
<div class="parent">
    <p>Dance like nobody is watching, code like everybody is.
    Dance like nobody is watching, code like everybody is.
    Dance like nobody is watching, code like everybody is.</p>
</div>
<style>
    .parent {
        height: 140px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        border: 2px dashed #f69c55;
    }
</style>
<div class="parent">
    <p class="child">The more technology you learn, the more you realize how little you know.
    The more technology you learn, the more you realize how little you know.
    The more technology you learn, the more you realize how little you know.</p>
</div>
 <style>
    .parent {
        display: table;
        height: 140px;
        border: 2px dashed #f69c55;
    }
    .child {
        display: table-cell;
        vertical-align: middle;
    }
</style>
块级元素垂直居中

使用absolute+负margin(已知高度宽度)
通过绝对定位元素距离顶部50%,并设置margin-top向上偏移元素高度的一半

<div class="parent">
    <div class="child">固定高度的块级元素垂直居中。</div>
</div>
.parent {
   position: relative;
}
.child {
   position: absolute;  
   top: 50%;
   height: 100px;
   margin-top: -50px;
}
<div class="parent">
    <div class="child">未知高度的块级元素垂直居中。</div>
</div>
.parent {
   position: relative;
}
.child {
   position: absolute;
   top: 50%;
   transform: translateY(-50%);
}
<div class="parent">
    <div class="child">未知高度的块级元素垂直居中。</div>
</div>
.parent {
    display:flex;
    align-items:center;
}
<div class="parent">
  <div class="child">Demo</div>
</div>
<style>
  .parent {
    display: table-cell;
    vertical-align: middle;
  }
</style>
上一篇 下一篇

猜你喜欢

热点阅读