How to center the triangle on a popover horizontally
I am using TailwindCSS on my React project and I'm currently creating a custom popover or a tooltip if you will. Everything seems good except I can't seem to center the small triangle outside of the container. It's looking a little bit towards the right even though I set left: 50%
.
<span
id='popover-last-seen'
className={classNames(
'absolute opacity-0 inline-block top-full left-1/2 -translate-x-1/2 -translate-y-20 px-3 py-2',
'bg-gray-700 text-xs text-center whitespace-nowrap rounded',
'transition duration-150 ease-in-out',
'after:content-[""] after:absolute after:w-0 after:h-0 after:border-4 after:border-gray-700 after:top-11 after:left-1/2 after:rotate-45'
)}>
<span className='block text-white'>
{standardTime(
timestampToDate(chatee.lastSeen)
)}
</span>
<span className='block text-gray-300 font-thin'>
{standardDateTime(
timestampToDate(chatee.lastSeen),
false
)}
</span>
</span>
I believe the problem here is the after:left-1/2
. I tried to do after:right-1/2
and it we开发者_开发知识库nt slightly towards the left. I'm not sure how to fix this.
According to MDN
When position is set to absolute or fixed, the left property specifies the distance between the element's outer margin of left edge and the inner border of left edge of its containing block. (The containing block is the ancestor to which the element is relatively positioned.)
Which means left: 50%
will not center element but his left border will be exactly at the parent's center. You can see it here - as blue element has some width it quite obvious it is not centered
In order to center it your need to move element itself backward on a half of its own width
CSS property for this is transform: translateX(-50%)
(where 50%
- half of elements width, minus
sign stands for moving backward). Tailwind's utility for this is translate-x-1/2
So your triangle should include after:left-1/2 after:-translate-x-1/2
or after:right-1/2 after:translate-x-1/2
精彩评论