aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/htmlimageelement/srcset/index.html
blob: b4a817c4d3a6daea35ef97cccaf2e1e959e31e7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
---
title: HTMLImageElement.srcset
slug: Web/API/HTMLImageElement/srcset
translation_of: Web/API/HTMLImageElement/srcset
---
<p>{{APIRef("HTML DOM")}}</p>

<p><span class="seoSummary">{{domxref("HTMLImageElement")}} свойство <code><strong>srcset</strong></code> </span>это строка, которая определяет один или несколько<span class="seoSummary"> <strong>строк с источниками изображений</strong>, разделённые запятыми (<code>,</code>) и условия для их использования.</span> Каждая строка предлагаемого изображения содержит <strong>URL</strong> картинки и опциональные <strong>ширину</strong> или <strong>пиксельную плотность</strong> которые указывают при каких условия это изображение должно быть использовано вместо основной картинки обозначенной свойством {{domxref("HTMLImageElement.src", "src")}}.</p>

<p>Свойство <code>srcset</code>, вместе с {{domxref("HTMLImageElement.sizes", "sizes")}}, критически важный атрибут при разработке адаптивных веб-сайтов, ведь они могут использоваться вместе для создания адаптивных страниц, использующих подходящие изображения при определённых условиях.</p>

<h2 id="Синтаксис">Синтаксис</h2>

<pre class="syntaxbox"><em>htmlImageElement</em>.srcset = <em>imageCandidateStrings</em>;
let <em>srcset</em> = <em>htmlImageElement</em>.srcset;
</pre>

<h3 id="Значение">Значение</h3>

<p>A {{domxref("USVString")}} containing a comma-separated list of one or more image candidate strings to be used when determining which image resource to present inside the {{HTMLElement("img")}} element represented by the <code>HTMLImageElement</code><em>.</em></p>

<p>Each image candidate string must begin with a valid URL referencing a non-interactive graphic resource. This is followed by a comma (<code>,</code>) character and then a condition descriptor that indicates the circumstances in which the indicated image should be used. Space characters, other than the whitespace separating the URL and the corresponding condition descriptor, are ignored; this includes both leading and trailing space, as well as space before or after each comma.</p>

<p>If the condition descriptor is not provided (in other words, the image candidate provides only a URL), the candidate is used as the fallback if none of the other candidates match. Otherwise, the condition descriptor may take one of two forms:</p>

<ul>
 <li>To indicate that the image resource specified by the image candidate string should be used when the image is being rendered with a particular width in pixels, provide a <strong>width descriptor</strong> comprised the number giving that width in pixels followed by the lower case letter "w". For example, to provide an image resource to be used when the renderer needs a 450 pixel wide image, use the width descriptor string <code>450w</code>. The specified width must be a positive, non-zero, integer, and <em>must</em> match the intrinsic width of the referenced image.</li>
 <li>Alternatively, you can use a <strong>pixel density descriptor</strong>, which specifies the condition in which th corresponding image resource should be used as the display's pixel density. This is written by stating the pixel density as a positive, non-zero floating-point value followed by the lower-case letter "x". As an example, to state that the corresponding  image should be used when the pixel density is double the standard density, you can give the pixel density descriptor <code>2x</code> or <code>2.0x</code>.</li>
</ul>

<p>You may mix and match the two types of descriptor. You must not, however, provide multiple image candidate strings that specify the same descriptor. All of the following are valid image candidate strings:</p>

<pre>"images/team-photo.jpg 1x, images/team-photo-retina.jpg 2x, images/team-photo-full 2048w"</pre>

<p>This string provides versions of an image to be used at the standard pixel density (<code>1x</code>) as well as double that pixel density (<code>2x</code>). Also available is a version of the image for use at a width of 2048 pixels (<code>2048w</code>).</p>

<pre>"header640.png 640w, header960.png 960w, header1024.png 1024w, header.png"</pre>

<p>This string provides versions of a header image to use when the {{Glossary("user agent", "user agent's")}} renderer needs an image of width 640px, 960px, or 1024px. An additional, fallback image candidate is provided without any condition at all, to be used for any other width.</p>

<pre>"icon32px.png 32w, icon64px.png 64w, icon-retina.png 2x icon-ultra.png 3x icon.svg"</pre>

<p>Here, options are provided for an icon at widths of 32px and 64px, as well as at pixel densities of 2x and 3x. A fallback image is provided as an SVG file that should be used in all other cases. Notice that the candidates may use different image types.</p>

<p>For more information on what image formats are available for use in the {{HTMLElement("img")}} element, see <a href="/en-US/docs/Web/Media/Formats/Image_types">Image file type and format guide</a>.</p>

<h2 id="Пример">Пример</h2>

<h3 id="HTML">HTML</h3>

<p>The HTML below indicates that the default image is the 200 pixel wide version of the clock image we use in several places throughout our documentation. Also specified by the <code>srcset</code> attribute is that the 200-pixel version should be used for 1x displays while the 400-pixel version should be used for 2x displays.</p>

<pre class="brush: html">&lt;div class="box"&gt;
  &lt;img src="/files/16797/clock-demo-200px.png"
       alt="Clock"
       srcset="/files/16864/clock-demo-200px.png 1x, /files/16797/clock-demo-400px.png 2x"&gt;
&lt;/div&gt;
</pre>

<h3 id="CSS">CSS</h3>

<p>The CSS simply specifies that the image and its surrounding box should be 200 pixels square and should have a simple border around it. Also provided is the {{cssxref("word-break")}} attribute, using the <code>break-all</code> value to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur.</p>

<pre class="brush: css">.box {
  width: 200px;
  border: 2px solid rgba(150, 150, 150, 255);
  padding: 0.5em;
  word-break: break-all;
}

.box img {
  width: 200px;
}</pre>

<h3 id="JavaScript">JavaScript</h3>

<p>The following code is run within a handler for the {{domxref("Window", "window")}}'s {{domxref("Window.load_event", "load")}} event.  It uses the image's  {{domxref("HTMLImageElement.currentSrc", "currentSrc")}} property to fetch and display the URL selected by the browser from the <code>srcset</code>.</p>

<pre class="brush: js">let box = document.querySelector(".box");
let image = box.querySelector("img");

let newElem = document.createElement("p");
newElem.innerHTML = `Image: &lt;code&gt;${image.currentSrc}&lt;/code&gt;`;
box.appendChild(newElem);
</pre>

<h3 id="Результат">Результат</h3>

<p>In the displayed output below, the selected URL will correspond with whether your display results in selecting the 1x or the 2x version of the image. If you happen to have both standard and high density displays, try moving this window between them and reloading the page to see the results change.</p>

<p>{{EmbedLiveSample("Example", 640, 320)}}</p>

<p>For additional examples, see our guide to <a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images">responsive images</a>.</p>

<h2 id="Спецификации">Спецификации</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('HTML WHATWG', '#dom-img-srcset', 'HTMLImageElement.srcset')}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">Браузерная поддержка</h2>



<p>{{Compat("api.HTMLImageElement.srcset")}}</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML">Images in HTML</a></li>
 <li><a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images">Responsive images</a></li>
 <li><a href="/en-US/docs/Web/Media/Formats/Image_types">Image file type and format guide</a></li>
</ul>