Skip to content Skip to sidebar Skip to footer

How To Horizontally Center An Annotation Above A Word In A Sentence?

I'd like to have a css object which let me place an annotation above a specific word of a sentence, or above a part of the sentence. The annotation must always be visibile and has

Solution 1:

You can center the annotation using left: 50%; transform: translateX(-50%);. The left attribute is in relation to the parent (50% of .highlight's width), while translateX is in relation to the element (-50% of .annotation's width).

p {
  font-size: 1.5em
}

.highlight {
  position: relative;
  display: inline-block;
  margin-top: 1em;
  color: red;
}

.highlight.annotation {
  position: absolute;
  /** remove width: 100%; **/left: 50%;
  bottom: 80%;
  transform: translateX(-50%);
  font-size: 0.75em;
  white-space: nowrap;
}
<p>short <spanclass=highlight>fo<spanclass=annotation>foo baar foo</span></span> but not centered.</p><p>long <spanclass=highlight>fooooooooooo<spanclass=annotation>foo baar foo</span></span> and centered.</p>

To make the annotation enlarge the annotated text, you can set .highlight to be an inline flexbox column (reversed), and align the items to the center:

p {
  font-size: 1.5em
}

.highlight {
  display: inline-flex;
  flex-direction: column-reverse;
  align-items: center;
  color: red;
}

.highlight.annotation {
  margin-bottom: 0.1em;
  font-size: 0.75em;
  white-space: nowrap;
}
<p>short <spanclass=highlight>fo<spanclass=annotation>foo baar foo</span></span> but not centered.</p><p>long <spanclass=highlight>fooooooooooo<spanclass=annotation>foo baar foo</span></span> and centered.</p>

Post a Comment for "How To Horizontally Center An Annotation Above A Word In A Sentence?"