Search code examples
cssalignment

CSS Text Alignment Issue (Subtext under paragraph)


I've got a CSS problem.

I have a div with a fixed width, and text inside it. The text is centered, and doesn't take up the entire width of the container.

I wish to have a piece of subtext directly under the centered text paragraph, but the subtext needs to be aligned to the right. Not the right of the container, but the right of the text (in this case it's a paragraph) so it lines up as I have illustrated below. The issue as I see it, is the paragraph width is not absolute.

How can I achieve this?

The black is the container, the text is the centered text, and the subtext needs to be aligned to the right of the paragraph width, not the container width. The green line indicates the centering of the paragraph text in the div container. The red lines are the dimensions of the paragraph, but this is dependent on the text and it's not a set value.

The paragraph 'text text text' will always be one line of variable length and therefore width. The subtext needs to align to the right of the paragraph width dynamically.

An illustration of the container, text, and subtext.


Solution

  • <div class="container">
        <p>
            centered text
            centered text
            <span>right text</span>
        </p>
    </div>
    

    CSS for that result.

    .container {
        text-align: center;
    }
    .container p {
        display: inline-block;
    }
    .container p span {
        display: block;
        text-align: right
    }