I have a layout where I need to position a horizontal line next to a multiline paragraph. The line should be vertically centered to the first line of the paragraph, not to the entire paragraph.
I’ve tried using CSS Flexbox to align the items, but it seems to center the line relative to the entire paragraph. How can I adjust the CSS to achieve this alignment?
Here is the HTML and CSS code I have so far:
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.container {
display: flex;
column-gap: 20px;
align-items: flex-start;
}
.line {
flex-shrink: 0;
width: 50px;
height: 2px;
background-color: red;
}
p {
margin: 0;
margin-bottom: 20px;
}
<div class="container">
<div class="line"></div>
<div class="text-container">
<p class="text">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</p>
<p class="text">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</p>
</div>
</div>
2
Answers
Use half the height of one line
.5lh
You can also simplify the code like below:
Super lazy option could be using just pseudo with "dash" (/em-dash/three-em-dash) from the very same font-face. In theory, such dash should be defined with vertical typographical balance in mind, usually positioned at or around the middle of the x-height, and naturally adjustable with ex-based transform if the outcome would end up be visually suboptimal when used as a "leader". Entire solution could be a single element with a single pseudo:
Translating it vertically by
+.5ex
should put it near baseline,-.5ex
should put it near x-height. Most probably will be quite font-dependent, but the general rule that such dash should "look good between regular glyphs" can establish assumption that there should not be super-wild variations of the vertical position relative to baseline between different fonts.This solution could even have some minor benefits over background variants in some environments:
Also, to put on the second, third etc. line, it is possible to add
white-space: pre
and prefix the pseudo content with a line break (a
).Possible drawback is that it is quite important for the font used to support given dash; if the dash would be picked from some fallback font-face, then the metrics will most probably be off.