Search code examples
csshtmlcenter

Center one of two sibling divs


In the following, I'd like to alter the CSS such that the right-sibling is truly centered in the container div. (Edit: without using absolute positioning).

<html>
  <head>
    <style type='text/css'>
      #container {
        width: 500px;
      }
      #left-sibling {
        float: left;
      }
      #right-sibling {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div id='container'>
      <div id='left-sibling'>Spam</div>
      <div id='right-sibling'>Eggs</div>
    </div>
  </body>
</html>

In its current implementation, the right sibling's centering is affected by the left sibling -- you can see this by adding display: none to the left-sibling's style.

(Note: I'd like to avoid modifying the HTML structure because, as I understand it, the whole point of CSS is to decouple the tag structure from the presentation logic, and this doesn't seem like a really crazy request for CSS to handle.)

TIA.


Solution

  • A trick I just used to get this to work is to have padding on the left of the container and we can encourage the left-sibling to sit inside this space by giving it an equal but negative margin.

    To complete the picture we also put padding on the right of the container of an equal size to the width of the left-sibling.

    <html>
      <head>
          <style type='text/css'>      
            #container {
                width: 500px;
                padding-left:50px;
                padding-right:50px;     
                }      
            #left-sibling {
                border: solid 1px #000;
                float: left;
                width:50px;
                margin-left:-50px;  
            }      
            #right-sibling {
                border: solid 1px #000;
                text-align: center;
    
            }
            #container2 {
                width: 500px;   
                }  
    </style>
      </head>
        <body>
            <div id='container'>      
                <div id='left-sibling'>Spam</div>
                <div id='right-sibling'>Eggs<br />Eggs<br />Eggs<br /></div>
            </div>
            <div id='container'> 
                <div id='left-sibling' style="display:none;">Spam</div>    
                <div id='right-sibling'>Eggs<br />Eggs<br />Eggs<br /></div>
            </div>
            <div id='container2'> 
                <div id='right-sibling'>Eggs<br />Eggs<br />Eggs<br /></div>
            </div>
          </body>
    </html>