Reputation: 1623
I'm trying to display an icon (font awesome) to the left of a heading, which currently works when the heading is on a single line, but the alignment gets messed up when the heading goes onto a second line.
What it currently looks like:
What I want:
Here's the simplest form of what I have (fiddle):
<div>
<h1><i class="fa fa-file-text fa-fw fa-lg"></i>Multi-line Title</h1>
</div>
I've tried separating the icon into a separate h1
, then float or inline display each of those, but because it's multi-line text none of that has worked.
What's a clean way to get this alignment I'm looking for?
Upvotes: 11
Views: 6826
Reputation: 36
Just found an easier way to solve this.
HTML:
<div>
<h1 class="icon">
<i class="fa fa-file-text fa-fw fa-lg"></i>
</h1>
<h1>Multi-line Title</h1>
</div>
CSS:
div {
width: 225px;
background-color: #ccc;
padding: 10px;
}
.icon {
display: inline;
}
h1 {
display: inline-block;
vertical-align: middle;
width: 55%;
}
The most important point is to change the width to a suitable value.
Working JSFiddle here: https://jsfiddle.net/hfqoj5d9/
Upvotes: -1
Reputation: 418
A little late to the party, but if anyone else is having the same issue - this is an easy fix with CSS Flexbox (which is a new...ish style, but by this point is pretty robustly supported).
(Note for code below: You can wrap the <i>
in a <div>
, or something else if necessary, but I would advise against including a second <h1>
tag as that could cause SEO issues. Basically, you need the .wrapper class with two children - one as the icon (or a div containing the icon), and one as the header.)
First, the new HTML:
<div>
<i class="fa fa-file-text fa-fw fa-lg"></i>
<h1>Multi-line Title</h1>
</div>
And the new CSS:
div {
display: flex;
align-items: center;
}
Note: align-items: center;
sets vertical alignment. This can also be flex-start (top-aligned) or flex-end (bottom-aligned) as desired.
Upvotes: 11
Reputation: 451
In this case, Using absolute positioning on the icon solves the problem. Besides, adjust it's top margin to align with the title text.
Fiddle: https://jsfiddle.net/0fadtcm7/
div h1 i {
position: absolute;
margin-left: -55px;
margin-top: 3px;
}
div h1 {
padding-left: 55px;
}
Upvotes: 0
Reputation: 7721
Add this
div h1 {
display: inline-block;
position: relative;
padding-left: 55px;
vertical-align: middle;
}
div h1 i {
position: absolute;
left: 0;
top: 50%;
margin-top: -10px; // half height of icon
}
Upvotes: 3