Belajar Element HTML: <img>

Tag <img> digunakan untuk menyematkan gambar ke dalam dokumen HTML.

Syntax

Tag <img> ditulis seperti <img src="" alt=""> (tanpa tag penutup) dengan URL gambar disisipkan di antara tanda kutip ganda dari atribut src.

Atribut alt menyediakan teks alternatif untuk pengguna yang tidak dapat melihat gambar.

Beberapa alasan pengguna tidak dapat melihat gambar mungkin karena koneksi internet lambat, salah penulisan URL lokasi gambar, dll.

<img src="gambar.jpg" alt="Gambar saya">
<img src="/images/html/sunset.jpg" alt="Picture of a Ha Long Bay sunset">
<!-- For responsive images, use srcset and sizes -->
<img src="/images/html/sunset-360.jpg" alt="Picture of a Ha Long Bay sunset" srcset="/images/html/sunset-360.jpg 360w,
    /images/html/sunset-720.jpg 720w,
    /images/html/sunset-1440.jpg 1440w>" sizes="(min-width: 800px) 720px, 360px">

src

URL tempat gambar dihosting.

Required.

"/images/html/tiramisu.jpg"

Kamu dapat menggunakan URL relatif .

"{{site.url}}/images/traffic.jpg"

Kamu dapat menggunakan URL absolut .

alt

Teks alternatif jika gambar tidak tersedia.

Required.

"Picture of a man standing in front of the Dragon's Pearl boat"

Menjelaskan gambar seolah-olah itu tidak ada.

srcset

Defines a list of different sources for the same image. The browser will choose the best one to use.

"/images/sunset-@2x.jpg 2x"

You can define a pixel density descriptor like 2x. In this case, sunset-@2x.jpg is 720px wide.

          <img src="/images/sunset.jpg" srcset="/images/sunset-@2x.jpg 2x" alt="Picture of a Ha Long Bay sunset">
          

The browser will either use sunset.jpg or sunset-@2x.jpg depending on the space available, the pixel density, etc.

"/images/sunset-360.jpg 360w,
/images/sunset-720.jpg 720w,
/images/sunset-1440.jpg 1440w"

You can use a width descriptor like 360w. This value is divided by one of the source sizes (defined in the sizes attribute) to obtain the pixel density.

          <img src="/images/sunset-360.jpg" alt="Picture of a Ha Long Bay sunset" srcset="/images/sunset-360.jpg 360w,
          /images/sunset-720.jpg 720w,
          /images/sunset-1440.jpg 1440w>" sizes="(min-width: 800px) 720px, 360px">
          

sizes

Defines a list of different source sizes. You can combine each of them with a media query.

"(min-width: 800px) 1440px, 720px"

The browser will use the 1440px image (defined in srcset) if the viewport is larger than 800px.
It will use the 720px otherwise.

          <img src="/images/sunset-360.jpg" alt="Picture of a Ha Long Bay sunset" srcset="/images/sunset-360.jpg 360w,
          /images/sunset-720.jpg 720w,
          /images/sunset-1440.jpg 1440w>" sizes="(min-width: 800px) 720px, 360px">
          

height

Defines the height of the image.

"240"

The height in pixels.

width

Defines the width of the image.

"120"

The width in pixels.

Pengaturan Default CSS

Sebagian besar browser menampilkan elemen <img> dengan pengaturan CSS:

img {
  display: inline-block;
}