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
imgin the first paragraph of this section. Use this src:http://wudesign.me/resources/using-images/images/smiley.jpg. -
Be sure to include the
altattribute, 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
imgbelow this set of instructions. Use src:http://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.
-
Add another
imgafter this set of instructions. Again, use src:http://wudesign.me/resources/using-images/images/shelf-cloud-wide.jpg. -
This time, add
class="square"to the tag, and use that class as the selector for a style rule that setswidth: 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
.squareruleset, 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 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
.squareruleset, 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%.
36KB
138KB
422KB