Search code examples
htmlcsspositioning

How to position a row of text based on a particular letter?


I have a line of text as follow:

->A B C D E F G H I J                   <-

I want to position the line of text using CSS such that letter D is at the centre of the page as shown below:

->             A B C D E F G H I J      <-

Any idea?


Solution

  • If you use a monospaced font then you can use position:relative; and move your row of text, since every letter and space has the same size (demo). You can achieve a similar result on fonts without fixed-width, but the offset (left:;) is a little bit harder to calculate, as almost every letter occupies another amount of horizontal space.

    <nav class="letter monospace">
        <div>A B C D E F G H I J</div> <!-- monospaced font demo -->
    </nav>
    <nav class="letter">
        <div>A B C D E F G H I J</div> <!-- standard browser font demo -->
    </nav>
    <div id="leftmiddle"> </div>
    <div id="rightmiddle"> </div>
    
    nav.letter{
        font-size:2em;
        text-align:center;
    }
    nav.letter > div{ /* standard browser font */
        position:relative;
        left:1.05em; /* you have to calculate the horizontal shift yourself based on the font you're using */
    }
    nav.letter.monospace{
        font-family:monospace;
    }
    nav.letter.monospace > div{ /* monospaced font */
        position:relative;
        left:1.75em; /* to center the row around 'E' change to 0.75em, for C to 2.75em... */
    }
    
    nav ~ div{
        width:49%;
        min-height:200px;
        height: 80%;    
    }
    #leftmiddle{ float:left;    border-right:1px solid;}
    #rightmiddle{    float:right;    border-left:1px solid;}
    

    HTML4 demo, working in IE7-9, FF10, Opera, Chrome.

    UPDATE: See this alternative demo (working in IE7-9, FF10, Opera, Chrome):

    <div class="letter">
        <div class="wrapper">
            <div class="before">
                A B C
            </div>
            D       
            <div class="after">
                E F G H I J
            </div>
        </div>
    </div>
    
    .letter{
        text-align:center;
        overflow:hidden;
    }
    .letter > .wrapper{
        width:1em;
        margin:auto;
        position:relative;
    }
    .letter > .wrapper > .before{
        position:absolute;
        right:125%;
        text-align:right;
        width:10em;
    }
    .letter > .wrapper > .after{
        position:absolute;
        text-align:left;
        top:0;
        left:125%;
        width:20em;
    }