ajmajmajma ajmajmajma - 5 months ago 23
CSS Question

centering psuedo element "caret" without position relative

I have a small caret I am using for a hoverstate on some menu items. Hovering just adds a little class called

menu-caret
which I add a psuedo element to add a little caret.

The css for the carret just looks 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;
}


The problem I am having is, I would like to center each caret (the menu items are dynamic in size/width, but also keep the integrity of the hover sub menu I have in place here

Here is ia full working example (without the caret fix ) - http://codepen.io/ajmajma/pen/KgGxWL

I know I could do something like this :

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


But in adding the position relative, it will mess with the sub menu size (it should be 100% page width). Is there any way to have a centered caret without messing with my sub menu? Thanks!

Answer

You can change the relative container on which you are creating the caret. For example move it to the a tag:

.menu-caret > a::after {
  content:"";
  position: absolute;
  left:50%;
  margin-left: -5px;
  bottom: -10px;
  width: 0%;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 5px solid black;
}
.menu > ul > li a {
  position: relative;
}

CodepenDemo