Images, centering, and responsiveness

One of my first projects was to make a front page for a website, the sort of thing with an “Enter Site” link on it. It is mostly images, and I learned a lot about manipulating images in setting the page up and making it responsive.

All of the following require setting a position attribute. Fixed, relative, absolute – anything but the default static.

At a small screen width I just use percentages for width.

width: 60%;
left: 20%; // that is, half of 100-60

will center an image or the div containing it. If you apply it to the image and the image is smaller than 60% of the current screen width it will expand to fit. If you apply it to a containing div and leave the image unstyled, then the image will appear in its natural size, extending outside the div if necessary. Styling the image with width: 100%; makes it fill the div exactly, regardless of its natural size.

For larger screens width by percentage isn’t as useful for images. I do not remember where I found this trick, but you can center a smaller image or div on a wide page with percentages and negative margins.

top: 50%;
left: 50%;

will center the top left corner of the image or div. Suppose the element is 250px wide and 400px tall. Add margins to shift the element so its center is centered.

margin-top: -200px;
margin-left: -125px;

I used this technique to make sure the background image was centered regardless of browser window width, and, with appropriate margin adjustments, to stack a second div below the one in the center of the screen.

Leave a Reply

Your email address will not be published. Required fields are marked *