The img
tag
Basic syntax for the img
tag
The img
tag is the simplest and most common way to display an image in an html page. It requires a src
attribute, which indicates where the browser will find the image, and an alt
attribute, which provides a textual version of the image for screen-readers.
img src="path/to/image.jpg" alt="My image"
- Add an
img
in the first paragraph of this section. Use this src:https://wudesign.me/resources/using-images/images/smiley.jpg
. - Be sure to include the
alt
attribute, with a meaningful value.
An img
element is, by default, an inline element, so it will wrap with other inline elements on the page.
Sizing an img
img
tags can be sized with CSS. Like other elements, you can add an id, class, or other attributes as you see fit in order to assist with styling. Generally, it is best to set only width or height, not both. If you set only one, the browser will set the other automatically in order to maintain the aspect-ratio of your image source file.
- Add an
img
below this set of instructions. Use src:https://wudesign.me/resources/using-images/images/shelf-cloud-wide.jpg
. - The image will be huge. So, add
class="full-screen"
to the tag, then use that class as the selector for a style rule that setswidth: 100%;
on the image.
Cropping an img
Sometimes your source image doesn't match the aspect-ratio of the space you need to fill. What if we want to put our wide image into a square? First, let's try just setting both width and height.
img
after this set of instructions. Again, use src: https://wudesign.me/resources/using-images/images/shelf-cloud-wide.jpg
.class="square"
to the tag, and use that class as the selector for a style rule that sets width: 280px; height: 280px;
on the image.The image is stretched! Not what we wanted. We need to tell the image to be cropped, not stretched.
- On your
.square
ruleset, addobject-fit: cover;
Now the image is cropped, instead of stretched. The cover
value tells the browser to scale the image proportionally such that it just covers the entire area of the img
tag, but no larger. (You can also use the contain
value, which scales the image proportionally to fit entirely inside the area of the img
tag.) The image will be centered by default, but the center is not really the best part of this particular image, so let's reposition it.
- On your
.square
ruleset, addobject-position: left center;
The object-position
value can have two parts, the first for the horizontal position, the second for vertical position. We can use words like left
, right
, and top
, or numerical values like 100px
or 20%
.