user1038814
user1038814

Reputation: 9667

Aligning image on multiple H1 tag lines

I have an image in an h1 tag which is vertically aligned in the middle. It works well with a short sentence. However, when the sentence is on multiple lines, I'd like the image to be aligned in the middle of the entire sentence rather than just the first line. Is there anyway to do this without creating two columns?

<h1><img src="https://images-na.ssl-images-amazon.com/images/I/4109Z2o0HuL._SX522_.jpg" height="35" style="padding-right:20px; vertical-align: middle;">Hello, how are you?</h1>
<h1><img src="https://images-na.ssl-images-amazon.com/images/I/4109Z2o0HuL._SX522_.jpg" height="35" style="padding-right:20px; vertical-align: middle;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</h1>

Upvotes: 1

Views: 49

Answers (2)

Huangism
Huangism

Reputation: 16438

You can achieve this with flex

https://jsfiddle.net/yc9umsop/

h1 {
  display: flex;
  align-items: center;
}

HTML

<h1>
   <img src="https://images-na.ssl-images-amazon.com/images/I/4109Z2o0HuL._SX522_.jpg" height="35" style="padding-right:20px; vertical-align: middle;">
   <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</span>
</h1>

Note I wrapped your text with a span

Learn how to use flex here https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Upvotes: 3

Jako Basson
Jako Basson

Reputation: 1531

Well if you absolutely don't want to create multiple columns then you could go with this pure css approach :

h1{
  position:relative;
  padding-left:80px;
}

h1 img{
  position:absolute;
  left:5px;
  top:50%;
  margin-top:-17.5px; /* IMAGE HEIGHT DIVIDED BY 2 */
}

https://jsfiddle.net/cndj27q3/4/

My suggestion would be to go with an additional html element instead using a multi column approach if at all possible in your scenario.

Hope that helps.

Upvotes: 1

Related Questions