Câu hỏi phỏng vấn HTML
Câu hỏi

Why you would use a srcset attribute in an image tag? Explain the pr...

Câu trả lời

The srcset attribute is used in an image tag to specify a list of different image sources for the browser to choose from, based on certain conditions such as the device's screen size, resolution, and pixel density. This attribute is a key component in creating responsive images that adapt to various display scenarios, ensuring that users receive an image with the best possible resolution and size for their device, without unnecessary data usage or loss of image quality.

When a browser encounters an image tag with a srcset attribute, it follows a process to determine which image source to use:

  1. Device Characteristics: The browser first checks the device's characteristics, including its screen width, pixel density (device-pixel-ratio), and potentially other factors like network conditions.

  2. Evaluating srcset: The srcset attribute contains a comma-separated list of image URLs, each followed by a space and a descriptor. There are two types of descriptors:

    • Width Descriptors (w): These specify the width of the image in pixels (e.g., image-240.jpg 240w). The browser uses these descriptors in conjunction with the sizes attribute to calculate the most appropriate image to display.
    • Pixel Density Descriptors (x): These specify the image's intended pixel density (e.g., image-2X.jpg 2x). The browser uses these descriptors to select images for devices with different pixel densities, such as Retina displays.
  3. Evaluating sizes: If width descriptors are used in srcset, the sizes attribute must also be present. The sizes attribute defines a set of media conditions (e.g., (max-width: 600px) 100vw, 50vw) and the corresponding size of the image for each condition. The browser matches the current viewport against these conditions to determine which s...

senior

senior

Gợi ý câu hỏi phỏng vấn

middle

What does a DOCTYPE do?

junior

How Can I Get Indexed Better by Search Engines?

middle

What are defer and async attributes on a