2

I've built a flexbox calendar layout that contains CSS tooltips on hover. I'm trying to vertically align these tooltips in relation to the calendar date they correspond to.

I'd like to achieve this in CSS, but have been unable to. At the moment, I've set a left value of 4em and dynamically calculated the top value in jQuery since the height of these tooltips can vary. Even in doing so, the tooltips are not perfectly vertically aligned and I'm not sure why.

Here's my jQuery function:

$('.cal-tooltip').each(function() {
  var calTooltipHeight = $(this).outerHeight(true) / 2;

  $(this).css('top', -calTooltipHeight);
});

CSS:

.tooltip {
  position: absolute;
  z-index: 1;
  background-color: white;
  box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.2);
}
.tooltip:after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  margin-left: -15px;
  margin-top: -15px;
  top: 50%;
  box-sizing: border-box;
  border: 15px solid black;
  border-color: transparent transparent white white;
  transform-origin: 50% 50%;
  box-shadow: -5px 5px 10px 0 rgba(0, 0, 0, 0.1);
}
.tooltip > div {
  padding: 15px;
}
.tooltip > div:not(:first-child) {
  padding-top: 5px;
}
.tooltip > div img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.tooltip-left:after {
  left: 0;
  transform: rotate(45deg);
}

.tooltip-right:after {
  left: 100%;
  transform: rotate(-135deg);
}

#event-calendar .cal-tooltip {
  display: none;
  width: 20em;
  cursor: auto;
}
#event-calendar .cal-tooltip .cal-tooltip-cont {
  display: flex;
}
#event-calendar .cal-tooltip .cal-tooltip-cont > div {
  flex-basis: 50%;
}
#event-calendar .cal-tooltip .cal-tooltip-cont > div:nth-child(1) {
  padding-right: 7.5px;
}
#event-calendar .cal-tooltip .cal-tooltip-cont > div:nth-child(2) {
  padding-left: 7.5px;
}
#event-calendar .cal-tooltip .cal-tooltip-cont > div h2,
#event-calendar .cal-tooltip .cal-tooltip-cont > div h3 {
  font-size: 0.75em;
}
#event-calendar .cal-tooltip .cal-tooltip-cont > div h2 {
  padding-bottom: 5px;
}
#event-calendar .tooltip-left {
  left: 4em;
}
#event-calendar .tooltip-right {
  right: 4em;
}

Demo: CodePen

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Mario Parra
  • 1,504
  • 3
  • 21
  • 46

1 Answers1

6

An absolutely-positioned element is aligned relative to the nearest positioned ancestor. Make that ancestor the tooltip's container:

table-cell { position: relative; }

Then, instead of using pixels for alignment, use a percentage:

.tooltip { top: 50%; transform: translateY(-50%); }

With that adjustment to your code...

enter image description here

The tooltips are vertically aligned with the date:

enter image description here

More details here: Element will not stay centered, especially when re-sizing screen

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701