JROB JROB - 6 months ago 15
HTML Question

Vertical aligning :after element within parent container (jsfiddle)

I am trying to vertical align text to the center of it's parent container, but it is aligning a little farther down than center.

Here is the fiddle: 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>

Answer

Add transform: translateY(-50%); to your .caret-right:after rule:

.caret-right:after {
    transform: translateY(-50%);
}

This correctly offsets your element 50% of its height to vertically center your caret:

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

Comments