Reputation: 12297
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.
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:
Upvotes: 38
Views: 54140
Reputation: 78686
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.
Upvotes: 12
Reputation: 288260
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>
Upvotes: 93
Reputation: 46785
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>
Upvotes: 1