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

心已入冬 提交于 2019-12-09 16:16:04

问题


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 span and a link. I'd like the span to align to the left and the link to align to the right.

http://jsfiddle.net/Lkfacta3/

h1>span {
  text-align: left;
}
h1>a {
  text-align: right;
}
 <h1><span>Align me left</span> <a href="">align me right</a></h1>

This is the desired result:


回答1:


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>



回答2:


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.




回答3:


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>


来源:https://stackoverflow.com/questions/29572539/css-align-two-element-to-the-left-and-right-in-the-same-line-without-floats

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