klotz
klotz

Reputation: 3

Keep center alignment for one element not the whole line

I've been trying to center text and put more text in the same line right next to it, while keeping the whole thing centered on the first text and not the whole line. Is there an easy way to do this?

All the solutions that I tried so far were either centering on the whole line or failed to put everything on the same line. Of course I also searched through stackoverflow but could not find a solution. I've made this as a mockup: http://jsfiddle.net/mzqC5/

The way it should behave is that the alignment is centered on "A" and not the whole line. I'd appreciate any help with it since I've been trying to solve this for a good time now.

Thank you very much.

<div class="centered">A<div class="subtext">[24]</div>

.centered {
font-family: Meiryo, sans-serif;
font-size: 75px;
text-align: center;
color: black;
background-color: cornflowerblue;
max-width: 175px;
margin: 0 auto;
}
.subtext {
font-family: Arial;
font-size: 24px;
display: inline-block;
}

Upvotes: 0

Views: 225

Answers (2)

ralph.m
ralph.m

Reputation: 14345

You could set it up like this (red line added just to demonstrate page center):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>

div {
    text-align: center; 
    height: 100%;
}

span {
    position: relative;
}

b {
    position: absolute; 
    left: 100%; 
    font-weight: normal;
}


html, body {height: 100%;}
body {padding: 0; margin: 0;}
div::after {content: ''; height: 100%; width: 2px; background: red; left: 50%; margin-left: -1px; position:absolute;}
</style>
</head>
<body>

<div>
    <span>
        A
        <b>[24]</b>
    </span>
</div>

</body>
</html>

Upvotes: 0

Andy G
Andy G

Reputation: 19367

One way to achieve this is to absolutely position [24] with the relatively-positioned A.

.centered {
    font-family: Meiryo, sans-serif;
    font-size: 75px;
    text-align: center;
    color: black;
    background-color: cornflowerblue;
    max-width: 175px;
    margin: 0 auto;
    position: relative;
}
.subtext {
    font-family: Arial;
    font-size: 24px;
    display: inline-block;
    position: absolute;
    bottom: 24px;
}

enter image description here

Because the element is absolutely-positioned it is not in the document-flow and doesn't affect the text-alignment.

You can adjust bottom to move it higher up.

Upvotes: 2

Related Questions