水平居中和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>

  效果如圖:html

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

以下代碼:spa

html:3d

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

 

樣式:code

.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; }

 

如圖:orm

 最終樣式改成:htm

.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; }

相關文章
相關標籤/搜索