温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

css垂直居中元素的方法

发布时间:2020-07-02 11:56:47 来源:亿速云 阅读:147 作者:Leah 栏目:web开发

这篇文章运用简单易懂的例子给大家介绍css垂直居中元素的方法,代码非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

垂直居中

1.单行内联元素垂直居中

<div id="box">
     <span>单行内联元素垂直居中。</span>。
</div>
<style>
 #box {
    height: 120px;
    line-height: 120px;
    border: 2px dashed #f69c55;
    }
</style>

2.多行内联元素垂直居中

①利用flex布局(flex)

利用flex布局实现垂直居中,其中flex-direction: column定义主轴方向为纵向。这种方式在较老的浏览器存在兼容性问题。

<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>

css垂直居中元素的方法

②利用表布局(table)

利用表布局的vertical-align: middle可以实现子元素的垂直居中

<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>

3 块级元素垂直居中

①使用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;
}

②使用absolute+transform

当垂直居中的元素的高度和宽度未知时,可以借助CSS3中的transform属性向Y轴反向偏移50%的方法实现垂直居中。但是部分浏览器存在兼容性的问题。

<div class="parent">
    <div class="child">未知高度的块级元素垂直居中。</div>
</div>
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}

③使用flex+align-items

通过设置flex布局中的属性align-items,使子元素垂直居中。

<div class="parent">
    <div class="child">未知高度的块级元素垂直居中。</div>
</div>
.parent {
    display:flex;
    align-items:center;
}

④使用table-cell+vertical-align

通过将父元素转化为一个表格单元格显示(类似 <td> 和 <th>),再通过设置 vertical-align属性,使表格单元格内容垂直居中。

<div class="parent">
  <div class="child">Demo</div>
</div>
<style>
  .parent {
    display: table-cell;
    vertical-align: middle;
  }
</style>

关于css垂直居中元素的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI