I realize that when I center text, its enveloping element becomes as wide as possible to be able to display the text in the true center with correct linebreaks and alignment.
But, what if I want to align a subtitle on the left hand side of centered text?
In the above image I simulated the desired outcome with a margin on the ‘test’ element, but is there a way to dynamically align this?
My code:
* {
outline: 1px solid red;
}
.contain {
margin: 0 auto;
max-width: 350px;
}
.wrap {
margin: 0 auto;
padding: 80px 0;
}
.content {
background: #ff000030;
font-size: 32px;
position: relative;
text-align: center;
width: fit-content;
}
.sub {
/* margin-left:30px; */
position: absolute;
top: 0;
transform: translateY(-100%);
}
<div class="contain">
<div class="wrap">
<div class="content">
Lorem ipsum dolor sit amet.
<div class="sub">test</div>
</div>
</div>
</div>
If at all possible, I’d like to avoid using javascript for this, and just find a pure css solution.
3
Answers
A solution from the future using the Anchor Positioning: https://drafts.csswg.org/css-anchor-position-1/#anchoring
Not ready for production but can be tested on Chrome with experimental flag enabled.
I could get the effect you want only if the "test" text is before the centered one, and uses an
inline-block
display; you can test varying the centered text to change the position:I will leave it as an option, if you have the opportunity to arrange
<br>
: