abagshaw
abagshaw

Reputation: 6582

Position element at top right of wrapped text

The following simple scenario illustrates the desired result when the text is not wrapped:

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  margin-right: 300px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  position: absolute;
  top: 0;
}
<div class="container">
  <h1>
    The Wrapped Text
    <span class="above">Above</span>
  </h1>
</div>

If the margin-right on the <h1> element is increased slightly (forcing the text to wrap) the Above text is no longer positioned as desired.

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  margin-right: 350px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  position: absolute;
  top: 0;
}
<div class="container">
  <h1>
    The Wrapped Text
    <span class="above">Above</span>
  </h1>
</div>

It's vertical position is correct, but horizontally it is aligned relative to the right edge of the last word. Is there a way to horizontally align the Above <span> relative to the right edge of the last word on the longest line? This way the Above text would remain at the top right of the text block at all times (wrapped or single line).

Upvotes: 2

Views: 65

Answers (1)

agrm
agrm

Reputation: 3842

You can try combining display:flex on .container h1 and vertical-align: super on .container .above.

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  display: flex;
  margin-right: 350px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  vertical-align: super;
}
<div class="container">
  <h1>
    The Wrapped Text
    <span class="above">Above</span>
  </h1>
</div>

Upvotes: 1

Related Questions