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

我的未来我决定 提交于 2019-12-04 02:37:14

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>

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.

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!