# Vertically and horizontally center these HTML elements

I have an image and a text title that I'm trying to center in a div. I would like the image to be to the left of the title, and for both of these elements to be centered both horizontally and vertically in the div.

I've found one way to do it, by nesting the image inside of a paragraph. I'm assuming this is not the proper way to do it, but I haven't been able to figure out any other way.

Here is a jsfiddle: http://jsfiddle.net/FvpV3/

And here is the code:

<body>

<div style="text-align:center;">

<div style="background-color:#E4E4E4;min-height:50px;width:100%;">

<div style="display:inline-block;vertical-align:middle;">

<p style="float:left;">
<img src="cid:logo-img" style="float:left;"/>
</p>

</div>

</div>

<div>

<p>message</p>

</div>

</div>

</div>

</body>


Does anyone know of a better way to position the image and title?

You can have it as simple as this:

HTML:

<div class="dialog">
<img class="icon" src="cid:logo-img" />
<h1>Title</h1>
</div>
<div class="body">
message </div> </div>  CSS: .dialog { margin: 0 auto; width:50%; border : 1px solid #CFCFCF; border-radius:6px; background-color:#EFEFEF; text-align: center; } .dialog > *{ padding: 20px; } .dialog > .header { background-color:#E4E4E4; } .dialog > .header > *{ display:inline-block; vertical-align:middle; }  • Why the choice of an H1 tag for the title? Also significantly simpler than mine! Feb 25 '14 at 3:42 • @AdamZuckerman Titles are usually represented by <hN> tags. Bootstrap uses <h4> in their modal samples as well. In fact, I modeled my version from Bootstrap, minus the intricacies. Feb 25 '14 at 4:05 You can simplify your HTML to this: <div id="parent"> <div class="floaters right"><img src="cid:logo-img" /></div> <div class="floaters">Title</div> <div class="centerme">message</div>
</div>


By adding classes, you can re-use CSS on more than one HTML element. The class floaters is applied to both of the divs that make up the top line. The class right is only applied to the left div on the first line to make it right aligned.

The #parent:after is one example of a clearfix. There are several other versions of clearfixes.

* {
box-sizing: border-box;
}
#parent {
margin: 0px auto;
width: 50%;
border: 1px solid #CFCFCF;
}
#parent:after {
content: "";
display: table;
clear: both;
}
.floaters {
float: left;
background-color:#E4E4E4;
width: 50%;
height: 3em;
}
.right {
text-align: right;
}
.centerme {
float: left;
clear: both;
text-align: center;
background-color:#EFEFEF;
height: 3em;
width: 100%;