我正在尝试将文本垂直对齐到其父容器的中心,但是它比中心稍微偏向一点。
这是小提琴:https://jsfiddle.net/xrvo6txq/1/
CSS:
.caret-right {
position: relative;
display: block;
}
.caret-right:after {
position: absolute;
right: 5%;
top: 50%;
display: inline-block;
vertical-align: middle;
transition: .15s;
-webkit-transition: .15s;
-moz-transition: .15s;
font-family: FontAwesome;
content: "\f105"; /* fa-angle-right */
font-size: 1.5em;
}
.caret-right:hover:after {
right: 4%;
}
.box {
border: 1px solid #ccc;
padding: 1em;
}
.align-center {
text-align: center;
}
HTML:
<a class="caret-right" href="#" title="Get Started">
<div class="box">
<p class="align-center">Get started now with <span class="color-theme-a">5 free lessons</span>.</p>
<p class="align-center">No credit card needed</p>
</div>
</a>
答案 0 :(得分:1)
将transform: translateY(-50%);
添加到您的.caret-right:after
规则:
.caret-right:after {
transform: translateY(-50%);
}
这正确地将你的元素50%的高度偏移到垂直居中你的插入符号:
.caret-right {
position: relative;
display: block;
}
.caret-right:after {
position: absolute;
right: 5%;
top: 50%;
transform: translateY(-50%);
display: inline-block;
vertical-align: middle;
transition: .15s;
-webkit-transition: .15s;
-moz-transition: .15s;
font-family: FontAwesome;
content: "\f105";
/* fa-angle-right */
font-size: 1.5em;
}
.caret-right:hover:after {
right: 4%;
}
.box {
border: 1px solid #ccc;
padding: 1em;
}
.align-center {
text-align: center;
}
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" />
<a class="caret-right" href="#" title="Get Started">
<div class="box">
<p class="align-center">Get started now with <span class="color-theme-a">5 free lessons</span>.</p>
<p class="align-center">No credit card needed</p>
</div>
</a>
&#13;
答案 1 :(得分:1)
要完全垂直居中.caret-right:after
,请保留50%top
值并添加以下内容:
transform: translateY(-50%);
答案 2 :(得分:0)
使用CSS3 transform
属性的另一种方法是为行高.caret-right
指定一个特定值,然后使用负上边距到行高的一半。< / p>
就个人而言,我更喜欢transform: translateY(-50%)
规则,但知道如何使用其他方法做到这一点很好。
.caret-right {
position: relative;
display: block;
}
.caret-right:after {
outline: 1px dotted red;
position: absolute;
right: 5%;
top: 50%;
display: inline-block;
transition: .15s;
-webkit-transition: .15s;
-moz-transition: .15s;
font-family: FontAwesome;
content: "\f105";
/* fa-angle-right */
font-size: 1.5em;
line-height: 50px;
margin-top: -25px;
}
.caret-right:hover:after {
right: 4%;
}
.box {
border: 1px solid #ccc;
padding: 1em;
}
.align-center {
text-align: center;
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet"/>
<a class="caret-right" href="#" title="Get Started">
<div class="box">
<p class="align-center">Get started now with <span class="color-theme-a">5 free lessons</span>.</p>
<p class="align-center">No credit card needed</p>
</div>
</a>
&#13;