Basic syntax for 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
imgin the first paragraph of this section. Use this src:
- Be sure to include the
altattribute, with a meaningful value.
img element is, by default, an inline element, so it will wrap with other inline elements on the page.
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
imgbelow this set of instructions. Use src:
- 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 sets
width: 100%;on the image.
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.
- Add another
imgafter this set of instructions. Again, use src:
- This time, add
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
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
imgtag.) 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
object-position: left center;
object-position value can have two parts, the first for the horizontal position, the second for vertical position. We can use words like
top, or numerical values like