문제

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.

Thanks.

<html>
<head>
    <title>Alignment Test</title>
    <style>
        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;}
    </style>
</head>
<body>
    <div id="reference">
        <div id="half1">Middle of container -->&nbsp;</div>
        <div id="half2"></div>
    </div>
    <div id="container">
        <div id="centered">This text should be centered
            <div id="floatLeft">This text should be left aligned</div>
        </div>
    </div>
</body>

도움이 되었습니까?

해결책

<div style="text-align:center;position:relative">
    Centered
    <div style="position:absolute;left:0;top:0">Left</div>
</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>
  centered
</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.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top