I'm sure this is a basic question to those of you who work in HTML and CSS regularly.

I have two pieces of text, both need to appear on the SAME line - one needs to be left aligned, and the other needs to be centered, regardless of how much text is in the left-aligned block (obviously while the length of the left-aligned text does not extend over the halfway mark).

To make this easier to understand and test, I have included a sample. In my sample, I have what I need, but on 2 lines instead of the same line.

Please repost the working sample if you find a solution.


    <title>Alignment Test</title>
        body {background-color: #E6E6E6;}
        #reference {width: 100%;
                    border: solid 1px navy;}
        #half1 {width: 50%;
                text-align: right;
                border-right: dotted 1px navy}
        #container {width: 100%;
                    text-align: center;
                    border: solid 1px navy;}
        #floatLeft {float:left;
                    border: dotted 1px green;
                    background-color: #D0F5A9;}
        #centered {width: 100%;
                      border: dotted 1px red;
                      background-color: #F5F6CE;}
    <div id="reference">
        <div id="half1">Middle of container -->&nbsp;</div>
        <div id="half2"></div>
    <div id="container">
        <div id="centered">This text should be centered
            <div id="floatLeft">This text should be left aligned</div>

Was it helpful?


<div style="text-align:center;position:relative">
    <div style="position:absolute;left:0;top:0">Left</div>


Y. Shoham's solution works. Here's another, which handles wrapping content more gracefully (does not allow overlap between center and left section), but which requires changing the order of items in the markup:

<div style="text-align: center; overflow: auto;">
  <div style="float: left; text-align: left;">left</div>

(The text-align: left may not make a difference, eg if there's no width specified and nothing inside has an inherent width, like an image.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow