Search code examples
htmlcsscss-float

html align element relative to parent that has a width


given the html below. without changing any properties of the main element, how can i make the html element with id left/right be aligned to the left/right of the main element?

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      main {
        width: 400px;
        margin: auto;
        border: 5px solid green;
        text-align: center;
      }
      #left {
        border: 5px solid red;
      }
      #right {
        border: 5px solid blue;
      }
    </style>
  </head>
  <body>
    <main>
      <span id="left">left</span>
      <span id="right">right</span>
      <div>content below left and right</div>
    </main>
  </body>
</html>

using float: left (or right) does align the elements, but it affects how other elements are displayed relative to them.


Solution

  • You can use float left and right and then apply clear: both; to the following element/s.

    Addition after comment: "Normal" content floats next to floated elements, i.e. it's positioned at the left/right borders of the floated elements, as you obviously experienced when trying it. If you want the subsequent element/s to start below a floated element, you can add clear: left or right or both (try these options to see the effect).

    main {
      width: 400px;
      margin: auto;
      border: 5px solid green;
      text-align: center;
    }
    
    #left {
      border: 5px solid red;
      float: left;
    }
    
    #right {
      border: 5px solid blue;
      float: right;
    }
    #right + div {
      clear: both;
    }
    <!doctype html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Document</title>
    </head>
    
    <body>
      <main>
        <span id="left">left</span>
        <span id="right">right</span>
        <div>content below left and right</div>
      </main>
    </body>
    
    </html>