简体   繁体   中英

Align an image and text in same line

I want to align an image and h1 in the same line. I have attached my source code and it doesn't work. can someone tell what's wrong with it.

<head>
    .header img{
        float: left;
        width: 2px;
        height: 3px;
        background: #555;
    }
    .header h1{
        position: relative;
        top: 18px;
        left: 10px;
    }

    <title> home page </title>
</head>
<body>

    <div class="header">
        <img src="greenlock.jpg" alt="logo" />
        <h1> UNIVERCITY OF GREENLOCK <h1>        
    </div>

use display : inline-block

 .header img{ display:inline-block; width:10px; height:3px; background:#555 } .header h1{ display:inline-block; position: relative; } 
 <div class="header"> <img src="greenlock.jpg" alt="logo" /> <h1> UNIVERCITY OF GREENLOCK <h1> </div> 

you can also use float:left to image and float:right to the header

 .header img{ float:left; width:10px; height:3px; background:#555 } .header h1{ flaot:right; position: relative; } 
 <div class="header"> <img src="greenlock.jpg" alt="logo" /> <h1> UNIVERCITY OF GREENLOCK <h1> </div> 

Please try this code:

 .header img{
  width:2px;
  height:3px;
  background:#555;
  vertical-align: middle;

}
.header h1{
  display: inline-block;
  vertical-align: middle;
}

In a situation like this, where the image is essentially part of the heading , I would have the image which sits beside the <h1> , not as an <img> at all but as a background style rule applied to the <h1> :

 h1 { margin: 18px 0 0 10px; padding-left: 30px; font-size: 16px; line-height: 24px; text-transform: uppercase; background: url('http://placehold.it/24x24') no-repeat left top rgb(255,255,255); } 
 <header> <h1>University of Greenlock</h1> </header> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM