CSS: align two element, to the left and right in the same line without floats

后端 未结 3 1153
旧巷少年郎
旧巷少年郎 2020-12-10 03:54

I am trying to align two inline elements, one to the left and one to the right. I\'d like to accomplish this without using floats.

In my case, I have a h1, with a sp

相关标签:
3条回答
  • 2020-12-10 04:25

    You could try CSS tables, and take some precaution for dealing with the link if you want the active area to extend only over the text.

    Depending on how you want this to work in a flexible design, floats might be a feasible option.

    h1 {
      display: table;
      width: 100%;
    }
    h1 span, h1 a {
      display: table-cell;
    }
    h1 span {
      text-align: left;
    }
    h1 a {
      text-align: right;
      border: 1px dotted blue;
      width: 1%;
      white-space: nowrap;
    }
    <h1><span>Align me left</span> <a href="">align me right</a></h1>

    0 讨论(0)
  • 2020-12-10 04:26

    You can use some flexbox magic:

    h1 {
      display: flex;
      justify-content: space-between;
    }
    <h1>
      <span>Align me left</span>
      <a href="">align me right</a>
    </h1>

    0 讨论(0)
  • 2020-12-10 04:43

    You can use CSS display:table + display:table-cell.

    h1 {
      display: table;
      width: 100%;
      margin: 0;
    }
    h1>span {
      text-align: left;
      display: table-cell;
    }
    h1>a {
      text-align: right;
      display: table-cell;
    }
    <h1><span>Align me left</span><a href="#">align me right</a></h1>

    Or, do it with display:inline-block.

    h1 {
      font-size: 0; /* remove whitespace */
    }
    h1>span,
    h1>a {
      font-size: 32px;
      display: inline-block;
      width: 50%;
    }
    h1>span {
      text-align: left;
    }
    h1>a {
      text-align: right;
    }
    <h1><span>Align me left</span><a href="#">align me right</a></h1>

    Note, either way above will make the <a> clickable area larger, wrap it into another <span> if you need to correct that.

    0 讨论(0)
提交回复
热议问题