Home › Forums › CSS › Align text both left and right on the same line, but use different font-sizes.
- This topic is empty.
-
AuthorPosts
-
April 3, 2015 at 5:52 am #199648
everdimension
ParticipantIn this topic I propose one solution and encourage open discussion.
Often we need to push some text to the right of the line. Usually in titles when we want to display some kind of subtitle, maybe a post date or some controls.
Now this simple technique — https://css-tricks.com/left-align-and-right-align-text-on-the-same-line/ — works perfectly, but only if you use text with the same font-size.
What if I want my right text to be smaller? The lines no longer align to the same baseline.
Example (the problem):http://codepen.io/everdimension/pen/VYNgqv
And fixing this turned out to be not so simple.
I wanted to know what would be the best way to solve this problem.
I have come up with the following solution and I’m quite happy with it.
Example (the solution):http://codepen.io/everdimension/pen/zxbJRW
Basically, this is the solution code (css):
.text-left-right { text-align: right; position: relative; } .left-text { left: 0; position: absolute; } .right-text { font-size: 13px; /* declare any smaller font-size */ }
But it still has problems.
The first one is that when title texts become too long they will not wrap and will end up being overlapped.The second problem is that the right text always has to be smaller than the left text, but not vice versa. Although this particular issue can be solved using some modifier css classes.
I wonder if there are some commonly known techniques that I have not stumbled upon or if somebody can think of a better solution. Or may be just name some problems you can see with this one.
Surely one robust way would be to style the heading as table row and cells, using css
display: table-row
anddisaply: table-cell
rules. But although it’ll work, it is definitely not flexible when it comes to adding such styles as border-bottom to the whole heading.April 3, 2015 at 10:30 am #199699everdimension
Participantbearhead, not bad, but I see two issues:
First one is that you always have to calculate smaller text height and margin based on the bigger text.
Second one is that i’ve found inconsistent behavior when using floats for em’s, like
font-size: .7em;
and ‘margin-top: 1.3em;’ don’t seem to align the lines correctly. I don’t know why.Senff, also nice solution and one the first ones i thought about, but other than having always to know the font-sizes of both texts, I don’t really understand the formula behind
line-height
andheight
for the right text. Can you give more explanation as to what ratio should be kept in relation to the main text font-size? -
AuthorPosts
- The forum ‘CSS’ is closed to new topics and replies.