How to vertically center a horizontal line to the first line of a multiline paragraph using CSS?
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.
How can I adjust the CSS to achieve this alignment?
Here is the HTML and CSS code I have so far: https://jsfiddle.net/pmcdq1hr/1/
<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>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.text {
//padding-left: 70px;
}
.text:first-of-type {
background:
linear-gradient(red 0 0) no-repeat
0 calc(.5lh - 1px)/50px 2px;
}
p {
margin: 0 0 20px;
font-size: 20px;
}
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
7 Replies
You may be able to use the
::first-line
selector 🤔
That said, I would probably just use a pseudo element.
Assuming you know the line-height of the <p>, you could position the pseudo element that height, divided by 2, from the top.
Something like this might work:
This could of course be done with position absolute, it just depends on where you want the line to be and how it should affect the text.The problem is that the font size and line-height changes depending on the screen width. Can you perhaps think of a better solution?
how does the line-height change? As long as you use a custom property for that, you should be able to use that same one for the positioning.
I use SASS variables for font-size and line-height. This always changes depending on the media query.
$line-height-p-small: rem(20);
$line-height-p-medium: rem(24);
$line-height-p-large: rem(28);
$line-height-p-extra-large: rem(32);
$font-size-p-small: rem(14);
$font-size-p-medium: rem(16);
$font-size-p-large: rem(18);
$font-size-p-extra-large: rem(20);
@include small-screen {
p {
font-size: $font-size-p-small;
line-height: $line-height-p-small;
}
@include medium-screen {
p {
font-size: $font-size-p-medium;
line-height: $line-height-p-medium;
}
}
can't you use the same SASS variable for the top position calculation?
What do you mean? That I change the y position for every screen width I have?
You only define it once, just use the same variable as you already have for the line-height for the calculation.
I don't often use SASS but I believe that something like this might work:
So, adapting that to my previous suggestion, you might have this within your media queries:
(the rest of the pseudo styles would be defined as normal)
As I say, I am not overly familiar with SASS so I am not sure if this is possible.