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

时间:2022-09-24 20:38:44
<!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>

  效果如图:

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

注意的是,当左右居中内容可能超过一半,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:; 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:; 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; }

如图:

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

最终样式改为:

.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:; top:50%; transform: translateY(-50%);-webkit-transform: translateY(-50%); height: 1px; width: 100%; background-color: #fae5ca }
.oi_price_title span{ position: relative; z-index:; 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; }

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