水平居中和transform: translateY(-50%) 實現元素垂直居中效果


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>垂直居中</title>
    <style>
    * {
        margin: 0;
        padding: 0;
    }
    
    .center {
        width: 960px;
        height: 500px;
        margin: 0 auto;
        background: #1879D9;
    }
    
    .center p {
        background: #fff;
        position: relative;
        top: 50%;
        transform: translateY(-50%);
        left: 0;
        right: 0;
        margin: 0 auto;
        width: 100px;
    }
    </style>
</head>
<body>
    <div class="center">
        <p>垂直居中內容</p>
    </div>
</body>
</html>

  效果如圖:

 注意的是,當左右居中內容可能超過一半,iPhone5就會出現掉下來

如下代碼:

html:

<div class="oi_price_title"><span>付費項目:一生運勢詳批</span></div>

 

樣式:

.oi_price_title{ position: relative; text-align: center;font-size: 0.15rem;margin-bottom: 0.05rem;min-height: 0.24rem; text-align: center;}
.oi_price_title:before{ content: ""; position: absolute; left: 0; top:50%; transform: translateY(-50%);-webkit-transform: translateY(-50%); height: 1px; width: 100%; background-color: #fae5ca }
.oi_price_title span{ position: absolute; left: 50%; top:50%; transform: translate(-50%,-50%); -webkit-transform: translate(-50%,-50%); z-index: 1; background-color: #fcefdd; height: 0.22rem; line-height: 0.22rem; padding: 0 0.05rem; border:1px solid #fae5ca; border-radius: 3px; font-size: 0.14rem; }

 

如圖:

 最終樣式改為:

.oi_price_title{ position: relative; text-align: center;font-size: 0.15rem;margin-bottom: 0.05rem;min-height: 0.24rem; text-align: center;}
.oi_price_title:before{ content: ""; position: absolute; left: 0; top:50%; transform: translateY(-50%);-webkit-transform: translateY(-50%); height: 1px; width: 100%; background-color: #fae5ca }
.oi_price_title span{ position: relative; z-index: 2; background-color: #fcefdd; height: 0.22rem; line-height: 0.22rem; padding: 0 0.05rem; border:1px solid #fae5ca; border-radius: 3px; font-size: 0.14rem; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM