简体   繁体   中英

Centering the Pseudo-Element

So I am trying to center this triangle to the center of the a element using CSS, here is the CodePen: http://codepen.io/DerekDev/pen/yyjqvd

As you can see, when you hover over a menu item, the triangle is not center, but is off to the right side.

.menu a {
  color:#ffffff;
  text-decoration:none;
  font-family:'Roboto', sans-serif;
  font-size:24px;
  padding-left:20px;
  padding-right:20px;
  padding-top:23px;
  padding-bottom:23px;
  transition:.5s;
}
.menu a:hover:after {
  opacity:1.0;
}
.menu a:after {
  transition:.5s;
  opacity:0.0;
    width: 0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-top: 15px solid #217aa4;
  position:absolute;
  content:"";
  top:75px;
}
.menu a:hover {
  background-color:#217aa4;
}

Any help is appreciated.

The pseudo-element use absolute position, in this case you need to make relative the a parent:

.menu a {
  position:relative;
}

Then use a combination of left and translate to get the perfect center:

.menu a:after {
  position:absolute;
  content:"";
  top:100%;
  left:50%;
  transform:translateX(-50%)
}

CodepenDemo

Add this to your .menu a:after :

left: calc(50% - 37.5px);

And this to the .menu a :

position: relative;

Here's a Fiddle: http://jsfiddle.net/c9br43sv/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM