Styling Images Using CSS

Images on a web page are almost always one of three types: jpg, gif, or png. An HTML file tells the browser which images to place on the page and where to place them, but the images themselves aren't part of the HTML file. They are individual files that can be stored anywhere on the Internet.

images/articles/css/css06.webp

Images are inline elements, which means they do not start on a new line. Multiple images will be arrayed horizontally, if there is room for them. You can convert images into block elements using CSS.

img.normal {
display: block;
}

Now, images will not share horizontal space with other images. Even though the browser positions an image on the left by default, you can move it to the right using margins.

img.inset {
display: block;
margin-left: 1em;
}

Centering an image

To display image at the center,

display: block;
margin-left: auto;
margin-right: auto;

The auto tells the browser to split the left and right margins equally. The result is a centered image.

Floating images

To wrap some text around an image,

img {
float: left;
}

Now, any text that comes after the image in the HTML code will wrap around the image, on the right. If the text is too long to fit completely next to the image, it will continue at full width under the image. The image will share its horizontal space if there is room.

If you want text to wrap around the left side of the image,

img {
float: right;
}

When you do this, the browser places the text up against the image, leaving no breathing room. You can correct this by adding some margin to the image. For example, white space is added between the image and the text on its right. White space is also added below the image, to give breathing room between the image and any text that flows beneath the image.

img {
float: left;
margin: 0 .75em .5em 0;
}

Suppose you have a short paragraph wrapping around the side of an image such that it doesn't fill all the space to the left or right of the image. If you add another paragraph under the short paragraph, it will wrap. If you don't want this, you need to tell the browser to clear the float after the first paragraph. To do this, you create a class.

p.no-wrap {
clear: both;
}