Bits & Bytes

Centering HTML Elements

For our first example we want to center an image like this one:
XoaX.net Logo

This image is 260×50 pixels, but we are not concerned about the height because we are talking about centering the image horizontally with respect to the containing element.

If we knew the size of the containing element, we could find the center location and position the image there. However, we often deal with elements, like the browser window, that vary a great deal. In this case, we want to keep the image centered no matter how the containing element changes.

To center the image, we enclose it within a div, where we set the width to that of the image, and the right and left margins to auto, as shown below.

<div style="width: 260px; margin-left: auto; margin-right: auto;">
<img src="XoaXLogo.png" />
</div>

For illustration, we have put the 260×50 pixel image inside of a 480×100 pixel div and colored the background gray for illustration. Notice that the image sits at the top of the gray rectangle because we have not added anything to position it vertically.

Tags: , , , , , , , , ,

Michael Hall

By: Michael Hall

One Response to “Centering HTML Elements”

  1. Johnf231 says:

    Magnificent site. Plenty of useful information here. I’m sending it to some friends ans additionally sharing in delicious. And certainly, thanks in your sweat! dcbffacdfeff

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.