qadenza
qadenza

Reputation: 9293

How to vertically align an image inside a <h1> tag

HTML

<h1>abc abc<span><img class="goldT" src="btns/nav02.png"></span></h1>  

css

h1{
    margin:15px 0 15px 20px;
    font-size:1.1rem;
    font-weight:bold;
    background:#e1e1e1;
    padding-left:10px;
    color: #444444;
}
h1 span{
    float:right;
    margin-right:14px;
}
h1 .goldT{
    width:140px;
    vertical-align:middle;
}  

How can I keep img goldT vertically centered with header text abc.

Here is the FIDDLE

Upvotes: 17

Views: 20314

Answers (6)

Morpheus
Morpheus

Reputation: 9065

Edit 2023/03/03:

There are better ways to align elements nowadays:

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

CSS Grid can be used too, although I don't think it is best suited in this situation.


Original answer:

Just wrap text together with image into <span>:

<h1>
    <span>
        abc abc
        <img class="goldT" src="https://www.google.com/images/srpr/logo11w.png">    
    </span>
</h1>

FIDDLE

Upvotes: 2

Ukuser32
Ukuser32

Reputation: 2189

A much simpler solution is as follows:

<h1><span>abc abc</span><img class="goldT" src="btns/nav02.png"></h1>

On the h1 set a line-height and on the image and span set a vertical-align:middle;. Worked for me.

Upvotes: 4

Dinesh Kanivu
Dinesh Kanivu

Reputation: 2587

Try this here we can make image vertically center

Try this http://jsfiddle.net/SxxWV/10/

HTML

<div class="main">
<div class="box"><img  src="https://www.google.com/images/srpr/logo11w.png" />
</div>   
</div>

CSS

.main{ height:500px; border:1px red solid;position:relative}
.box{width:40px; height:40px; background:transparent; }

/* for centering */
img{width:100px}
.box { display: inline-block; width:100px }
.main{ text-align: center; }
.main:after{ content: ""; display: inline-block; height: 100%; vertical-align: middle; }

Upvotes: 3

codingrose
codingrose

Reputation: 15699

Try:

HTML:

<h1>
    <span class="text">abc abc</span><span class="span">
        <img class="goldT" src="https://www.google.com/images/srpr/logo11w.png">
    </span>
</h1>

CSS:

.span, .text {
    vertical-align:middle;
    display:table-cell;
}
h1 {
    display:table;
    width:100%;
}

Fiddle here.

Upvotes: 16

Bhavesh Kachhadiya
Bhavesh Kachhadiya

Reputation: 3962

you need to set css display style and vertical-align for the <h1>

see demo :http://jsfiddle.net/BhaveshKachhadiya/REHLZ/3/embedded/result/

Css for h1 :

h1{
    margin:15px 0 15px 20px;
    display:table-cell;
    vertical-align:middle;
    font-size:1.1rem;
    font-weight:bold;
    background:#e1e1e1;
    padding-left:10px;
    color: #444444;
}

Upvotes: 0

Aldi Unanto
Aldi Unanto

Reputation: 3682

Use margin-top. Ex : margin-top: -13px;

Sample

Upvotes: -8

Related Questions