skip to Main Content

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. You can also play with text-align and keep your elements as inline elements

    main {
      width: 400px;
      margin: auto;
      border: 5px solid green;
      text-align: justify;
    }
    main * {
      display: inline-block;
    }
    main div {
      width: 100%;
      text-align: center;
    }
    
    #left {
      border: 5px solid red;
    }
    
    #right {
      border: 5px solid blue;
    }
    <main>
      <span id="left">left</span>
      <span id="right">right</span>
      <div>content below left and right</div>
    </main>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search