ajmajmajma ajmajmajma - 1 month ago 9
CSS Question

center psuedo element content

I have a little "caret" that is put on my currently hovered menu item ,and I now realize the caret created it not centered. I have a bunch of dynamically sized menu items.

The class

menu-caret
is applied when hovered by a little bit of jquery, and I have some css like so :

.menu-caret::before {
content:"";
position: absolute;
margin-left: 20px;
bottom: 0;
width: 0%;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid black;
}


See a quick example here - https://jsfiddle.net/keL4zhky/3/.

Is it possible to have the carets be centered on the bottom? Thanks!

EDIT: is it possible to do this without relative? I have a full width sub menu that if i change the ul/li to relative will lose it's effect - See example here http://codepen.io/ajmajma/pen/KgGxWL

Answer

Just make the parent position: relative; and add left: 50%; and margin-left: -5px; to the pseudo element:

ul {
  width: 100%;
  position: relative;
  display: inline-block;
  list-style-type: none;
}
li {
  padding: 20px;
  float: left;
  position: relative;
}
.menu-caret::before {
  content: "";
  position: absolute;
  left: 50%;
  bottom: 0;
  width: 0%;
  margin-left: -5px;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 5px solid black;
}
<ul>
  <li class="menu-caret">one</li>
  <li class="menu-caret">larger</li>
  <li class="menu-caret">larrrrger</li>
</ul>

Instead of left: 50%; and margin-left: -5px;
you can also just use left: calc(50% - 5px);