Search code examples
cssalignment

How can I horizontally align the text in separate block elements?


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?

desired situation, 'test' lined out with 'Lorem'

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.


Solution

  • 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:

    * {
        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 {
        position: absolute;
        top: 0;
        transform: translateY(-100%);
        display: inline-block;
    }
    <div class="contain">
        <div class="wrap">
            <div class="content">
                <div class="sub">test</div>
                Lorem ipsum dolor sitametameta amet.  
            </div>
        </div>
    </div>