Visually Centering Images
Sometimes an image that is technically centered doesn't look quite centered when viewed. By technically centered, I mean with the same left and right, or top and bottom, margin measurements.
Something about the image just makes its position look somewhat off.
I'll show you how to move the image slightly from where it would otherwise be placed. Doing it this way, you won't have to change CSS that could affect other images that are okay as they are.
Here, the image is centered horizontally and vertically within the bordered box. We'll assume it doesn't look quite centered so we have an excuse to shift it around.
Here is the source code for the above. The image is centered within the div
.
<div style="text-align:center; border:1px solid #666; width:300px; height:300px; padding-top:87px; box-sizing:border-box;">
<img style="width:126px; height:126px;"
src="https://www.willmaster.com/possibilities/images/poss1280.jpg"
alt="example image">
</div>
Beginning at this point, the example code will have only the style for the img
tag. It is the only thing that changes. The code will be immediatley below the example it applies to.
The following examples will use position numbers large enough to be very clear which direction the image was moved. In your implementation, the movement can be as little as 1 pixel or as large as you wish.
To shift the image position, use the CSS position:relative;
declaration along with one of these properties: top
, right
, bottom
, or left
.
The CSS position:relative;
declaration does not change the flow of other content on the page. It only changes the position of the image.
With this first example, position:relative;
is used along with left:50px;
. The 50px
pushes the image away from the left edge.
style="position:relative; left:50px; width:126px; height:126px;"
To pull the image toward the left, use a negative value. The -50px
pulls the image left, like this:
style="position:relative; left:-50px; width:126px; height:126px;"
Each possible edge (top
, right
, bottom
, left
) can be used that way: A positive number pushes the image away from the indicated edge: A negative number pulls it in toward the indicted edge.
Here, the image is pulled toward the bottom.
style="position:relative; bottom:-50px; width:126px; height:126px;"
And here the image is pulled toward both the bottom and the left edges.
style="position:relative; bottom:-50px; left:-50px; width:126px; height:126px;"
When an image is centered but appears somewhat off, its position can be affected slightly with two CSS declarations. The examples above, having been used for instruction, use larger shifts to make the shift blatantly visible.
(This content first appeared in Possibilities newsletter.)
Will Bontrager