: элемент иллюстрации с необязательной подписью

HTML5 Element

HTML5 introduced the element, which lets you define more than one image.

Browser Support

Element
<picture> 13 38.0 38.0 9.1 25.0

The element works similar to the and elements. You set up different sources, and the first source that fits the preferences is the one being used:

Example


<picture>  <source srcset=»img_smallflower.jpg» media=»(max-width: 400px)»>  <source srcset=»img_flowers.jpg»>  <img src=»img_flowers.jpg» alt=»Flowers»></picture>

The attribute is required, and defines the source of the image.

The attribute is optional, and accepts the media queries you find in CSS @media rule.

You should also define an element for browsers that do not support the element.

Getting Started

I’m basing this example on SlimBootstrap, which is a skeleton application which uses the Slim Framework. Alternatively, you can clone or download the complete code for this tutorial from Github.

Once you’ve cloned or downloaded the skeleton application, there are a few more steps before beginning coding.

In this example I’m using ImageMagick, so you’ll need to ensure that it’s installed along with the Imagick PHP extension – refer to the installation instructions for details according to your operating system. If you prefer, you could always rewrite the example using GD or a library such as Imagine.

Then you’ll need to download the Picturefill library. I’ve placed the two relevant files – matchmedia.js and picturefill.js – in public/js/lib.

Create the configuration file config/config.php – there’s a skeleton example in the same folder – and add the following:

Finally, ensure that the images directory is both writeable by the web server, and it can create sub-directories – should do the trick. It is recommended you do the same for the logs directory – so that if you do run into any errors, they get conveniently printed there.

Summary

In this article I’ve described a possible solution to the issue of adaptive images by combining server-side, on-demand creation of image derivatives designed to be used with the Picturefill Javascript library. In time, a third-party Javascript library may well become redundant as standards such as evolve, but the need for server-side solutions is likely to remain.

Of course there’s no need to just use this code for using Picturefill or similar – it could also be used in, say, a content management system to generate different versions of an image for different displays. Can you think of anything else?

Background Images

Background images can also respond to resizing and scaling.

Here we will show three different methods:

1. If the property is set to «contain», the background image will scale, and try to fit the content area. However, the image will keep its aspect ratio (the proportional relationship between the image’s width and height):

Here is the CSS code:

Example

div {  width: 100%;  height: 400px;  background-image: url(‘img_flowers.jpg’);  background-repeat: no-repeat;  background-size: contain;  border: 1px solid red;}

2. If the property is set to «100% 100%», the background image will stretch to cover the entire content area:

Here is the CSS code:

Example

div {  width: 100%;  height: 400px;  background-image: url(‘img_flowers.jpg’);  background-size: 100% 100%;  border: 1px solid red;}

3. If the property is set to «cover», the background image will scale to cover the entire content area. Notice that the «cover» value keeps the aspect ratio, and some part of the background image may be clipped:

Here is the CSS code:

Example

div {  width: 100%;  height: 400px;  background-image: url(‘img_flowers.jpg’);  background-size: cover;  border: 1px solid red;}

Top picturefill Answerers

All Time

31

alexander farkas 11.5k33 gold badges3434 silver badges4040 bronze badges

17

Don Rhummy 18k2727 gold badges117117 silver badges222222 bronze badges

17

AidanCurran 1,93855 gold badges1717 silver badges2424 bronze badges

12

rspeed 1,3541111 silver badges2020 bronze badges

9

Sergiu Dumitriu 10.3k33 gold badges3232 silver badges5858 bronze badges

7

zcorpan 1,09055 silver badges1111 bronze badges

6

quietbits 17811 silver badge99 bronze badges

4

rebelliard 9,13266 gold badges3939 silver badges7777 bronze badges

3

René Schubert 86411 gold badge88 silver badges2727 bronze badges

3

fregante 20.2k1010 gold badges9090 silver badges117117 bronze badges

3

syanaputra 58055 silver badges1212 bronze badges

3

Jonah 14k1515 gold badges7474 silver badges139139 bronze badges

2

cloned 3,66222 gold badges1717 silver badges2828 bronze badges

2

Richie 41344 silver badges1212 bronze badges

2

aybe 11.6k66 gold badges4444 silver badges8585 bronze badges

2

Sergey S 2111 bronze badge

1

ReSedano 4,06522 gold badges99 silver badges2222 bronze badges

1

Harsh Aggarwal 14266 bronze badges

1

Tom Kentell 40622 silver badges1010 bronze badges

1

Chao 1,04077 silver badges1212 bronze badges

Тег

За адаптивность переживают не только разработчики сайтов но и разработчики браузеров. Как итог мы имеем тег <pictures>, который был предложен в 2011 году, как вариант тега <video> только с изображениями. Окончательно определились со спецификацией в 2014 и на данный момент <pictures> поддерживается в Chrome Opera и Firefox. Главное что нужно запомнить — тег <pictures> не работает без <img>. По сути это обёртка для тега <img> расширяющая его возможности. Иногда можно обойтись и без <picture> используя сокращённую запись. Что же такого интересного нам может предложить новый тег?

Главный недостаток тега <img> — только один атрибут src и следовательно одна картинка для всех экранов. Тег <picture> решает эту проблему. Рассмотрим пример

Первым атрибутом идёт обязательный атрибут src. Далее новый атрибут srcset, в котором перечисляются доступные изображения и их размер. Запись large_image.jpg 1000w означает что есть картинка large_image.jpg шириной 1000px. В атрибуте sizes перечисляются медиа-выражения для контрольных точек и соответствующие им размеры изображений. Размер указывается в vw(viewport width) — проценты от ширины окна.

Теперь о том как всё это работает. Предположим у нас браузер с шириной окна 900px. По правилу установленному в атрибуте sizes размер изображения будет 50% от 900px = 450px. Далее браузер выбирает лучший вариант из доступных. В нашем случае это будет medium_image.jpg.

В примере выше мы показываем браузеру возможные варианты оставляя за ним право выбора. Чтобы однозначно указать браузеру какое изображение показывать используем следующий код

Похоже на то, как задавать контрольные точки в адаптивной вёрстке. В атрибуте media элемента <source> мы определяем ширину окна, а в srcset соответственное изображение. Изображение из <img> пойдёт для браузеров не поддерживающих тег <pictures>.

Ещё один способ сберечь трафик посетителей — использовать изображения в формате WebP. Формат разработан в Google. Размер файла с изображением в формате WebP по сравнению с jpeg меньше на 25%. Проблема в том, что не все браузеры поддерживают этот формат. Новый элемент<picture> умеет отдавать браузерам только те картинки которые они могут отобразить. Для этого у элемента <source> в атрибуте type указываем формат изображения. Не забываем стандартный <img>, для тех кто не дружит с новыми форматами.


Тег <picture> поддерживается в Chrome и других браузерах на движке blink. В FireFox на данный момент(FireFox 36) поддержку нужно включать в настройках, а IE и Safari вообще ничего не знают о новом элементе. Не лучше обстоят дела с мобильными браузерами. Обычное дело для нового тега. Обеспечить поддержку для <picture> и соответствующих функций в браузерах, которые еще не поддерживают их, можно с помощью полифила Picturefill http://scottjehl.github.io/picturefill/.

Top picturefill Askers

All Time

15

Trott 45.2k1919 gold badges122122 silver badges170170 bronze badges

11

Don Rhummy 18k2727 gold badges117117 silver badges222222 bronze badges

11

Kortschot 96111 gold badge77 silver badges2020 bronze badges

7

dan 22933 silver badges1111 bronze badges

6

Andrew 75822 gold badges99 silver badges2121 bronze badges

5

David A. French 36944 silver badges2020 bronze badges

5

NthDegree 70977 silver badges2121 bronze badges

5

Jason 21011 silver badge66 bronze badges

5

Matt Rowles 5,4021717 gold badges4949 silver badges8282 bronze badges

4

chemoish 1,00422 gold badges1212 silver badges2020 bronze badges

4

mark 2,90955 gold badges2828 silver badges4141 bronze badges

4

xEmptyCanx 50822 gold badges1010 silver badges2222 bronze badges

3

amylynn83 17722 silver badges1717 bronze badges

3

duncanhall 8,37133 gold badges3737 silver badges7070 bronze badges

3

Caio Tarifa 5,6131111 gold badges4343 silver badges6969 bronze badges

2

Suresh Ungarala 2133 bronze badges

2

James 18211 silver badge1414 bronze badges

2

Sylvareth 10511 silver badge77 bronze badges

2

WesleySmits 49933 silver badges1212 bronze badges

2

JaydedDesigns 4311 silver badge88 bronze badges

Only non community-wiki questions and answers are included in these totals (updated daily)

Esempi

Alcuni esempi illustreranno le casistiche più comuni.

Stessa immagine a più risoluzioni

In questo caso viene fornita una copia esatta della stessa immagine, con la sola differenza della risoluzione (640, 800 e 1024px):

Il browser caricherà una delle tre immagini a seconda della densità dello schermo del client. Per ragioni di retro-compatibilità, viene specificato anche il valore dell’attributo , che fornisce l’immagine a risoluzione inferiore.

Il device pixel ratio del Samsung Galaxy 4 mini è pari a 1.5x

Immagini diverse su periferiche diverse: Art direction

È pratica comune quella di fornire immagini leggermente diverse a periferiche diverse. Ai browser mobili, ad esempio, si può fornire un particolare ingrandito dell’immagine originale. In questo caso è raccomandato il ricorso all’elemento e ad un elemento per ognuna delle immagini previste:

Dimensioni dello schermo e densità

All’interno dello stesso elemento possono essere stabiliti diversi criteri di selezione, assegnando un valore all’attributo e più valori valori all’attributo .

In questo caso il browser individua prima l’elemento in base alle dimensioni dello schermo (attributo media), quindi seleziona l’origine dell’immagine in base alla densità video della periferica.

La selezione in base alla viewport

Spesso le dimensioni effettive dell’immagine ci sono ignote in fase di progettazione, magari perché variano in proporzione rispetto alla viewport. Un’immagine di 600px che occupi l’intera larghezza dello schermo, ad esempio, corrisponde approssimativamente a su uno schermo di 320px di larghezza, ma a meno di su un tablet o un desktop.

In situazioni simili, possiamo ricorrere all’attributo sizes dell’elemento , come nel seguente esempio:

In questo caso, invece di specificare la densità per ogni immagine, viene specificata direttamente la dimensione di ognuna, in modo che il browser selezioni quella che meglio si adatti alla larghezza dello schermo. Allo stesso tempo, viene passata l’informazione, attraverso l’attributo , che l’elemento occuperà il 100% del viewport ( è una delle definite viewport units).

Invece di indicare al browser le dimensioni delle immagini, avremmo potuto calcolare la densità orizzontale dell’immagine: su uno schermo di 320px, un’immagine di 400px avrebbe avuto una densità pari a . Su uno schermo di 1240px, invece, un’immagine di 400px corrisponderebbe ad una densità di . Se cambiano le dimensioni dello schermo, quindi, cambia anche la densità delle immagini.

Selezione in base ai breakpoint del layout

Una media query fissa un breakpoint nel layout, ossia un limite riferito alle dimensioni del viewport, raggiunto il quale si passa da un layout ad un altro.

Ancora una volta, se non si sta facendo dell’art direction e le URL puntano a copie di dimensioni diverse della stessa immagine, l’elemento offre la soluzione più efficiente. Prendiamo ad esempio il seguente codice:

In questo esempio abbiamo fissato tre breakpoints: fino a 30em, l’immagine occuperà l’intera larghezza del viewport; da 30 a 50em, sarà proporzionata al 50% della larghezza disponibile; oltre i 50em, le dimensioni dell’immagine saranno calcolate per corrispondere al 33% del viewport meno 100px.

Fissati i breakpoint, sarà il browser a scegliere l’immagine che meglio si adatti alle dimensioni e alla densità dello schermo, con gran sollievo dello sviluppatore, che dovrà limitarsi a fornire un congruo numero di copie dell’immagine in diverse dimensioni.

Se avessimo fatto ricorso all’elemento , avremmo dovuto aggiungere un elemento per ognuna delle media query utilizzate. La soluzione offerta dall’elemento e dall’attributo sizes, invece, permette di ridurre il codice al minimo garantendo lo stesso risultato.

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors Colors RGB HEX HSL

CSS Backgrounds Background Color Background Image Background Repeat Background Attachment Background Shorthand

CSS Borders Borders Border Width Border Color Border Sides Border Shorthand Rounded Borders

CSS Margins Margins Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline Outline Outline Width Outline Color Outline Shorthand Outline Offset

CSS Text Text Color Text Alignment Text Decoration Text Transformation Text Spacing Text Shadow

CSS Fonts Font Family Font Style Font Size Font Google Font Shorthand

CSS IconsCSS LinksCSS ListsCSS TablesCSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float Float Clear Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar Navbar Vertical Navbar Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS Specificity

Image Paths and Routing

Here’s an example of the sort of path we’re going to provide:

Breaking that down;

is the images directory

is the derivative; in the following example this could also be , or


is a sub-directory – two-deep, in this example – for organising the images

is the filename

If the file referenced by this path exists then the browser will just fetch it, bypassing any routes we have set up. But it’s that route that we’ll need to define, in order to intercept requests for derivatives that don’t yet exist.

We can match all such requests using the following pattern:

The path above results in the $parts variable being populated as follows:

Extracting the relevant parts is easy, by whittling away at this array:

Because we’ve taken the derivative and filename out of the array, it doesn’t matter how many levels deep the file is, as we just implode the remaining array to create the path.

The next step is to check that the destination directory exists – and if not, create it.

The third argument to mkdir is important; it’s going to be nexcessary to recursively create directories.Configuring the Derivatives

Let’s create a flexible configuration which for each derivative, defines the name (which will form part of the URL), the appropriate size, and the corresponding media query.

Here’s an example in JSON:

In this example I’ve only defined widths, but the resize function I’m going to use allows you to define either the width or the height – or both. It also provides cropping functions, but for simplicity I’ll just use scaleImage – see the documentation for details.

Source

L’elemento source è utilizzato come nodo discendente degli elementi audio e video, ma l’ambito di utilizzo e gli attributi ammessi cambiano con l’introduzione dell’elemento : viene superato l’attributo , invece previsto in e , ed è diverso l’algoritmo di selezione della risorsa.

L’attributo media permette di stabilire una media query che il browser colloca in un foglio di stile nell’ordine in cui i rispettivi elementi source vengono definiti nel documento. Se manca l’attributo , questo viene interpretato come . Qualunque valore non valido viene ignorato dal browser.

La tabella che segue elenca gli attributi così come descritti dal WHATWG:

Attributo Descrizione
srcset obbligatorio, deve essere composto da una o più stringhe (), separate tra loro da virgola. La stringa deve essere composta da una valida URL, un eventuale spazio bianco, un eventuale descrittore di larghezza o di densità.
sizes se presente, il valore deve essere costituito da un elenco valido di dimensioni (em, rem, px, etc.).
media se presente, deve rappresentare una valida media query.
type se presente, il valore deve essere un valido MIME type. Un tipo non supportato implica che il browser passi alla risorsa successiva (come avviene nel caso di e ).

The Areas

Then, add the clickable areas.

A clickable area is defined using an element.

Shape

You must define the shape of the clickable area, and you can choose one of these values:

  • — defines a rectangular region
  • — defines a circular region
  • — defines a polygonal region
  • — defines the entire region

You must also define some coordinates to be able to place the clickable area onto the image. 

Shape=»rect»

The coordinates for come in pairs, one for the x-axis and one for the y-axis.

So, the coordinates is located 34 pixels from the left margin and 44 pixels from the top:

The coordinates is located 270 pixels from the left margin and 350 pixels from the top:

Now we have enough data to create a clickable rectangular area:

Example

<area shape=»rect» coords=»34, 44, 270, 350″ href=»computer.htm»>

This is the area that becomes clickable and will send the user to the page «computer.htm»:

Shape=»circle»


To add a circle area, first locate the coordinates of the center of the circle:

Then specify the radius of the circle:

pixels

Now you have enough data to create a clickable circular area:

Example

<area shape=»circle» coords=»337, 300, 44″ href=»coffee.htm»>

This is the area that becomes clickable and will send the user to the page «coffee.htm»:

Shape=»poly»

The contains several coordinate points, which creates a shape formed with straight lines (a polygon).

This can be used to create any shape.

Like maybe a croissant shape!

How can we make the croissant in the image below become a clickable link?

We have to find the x and y coordinates for all edges of the croissant:

The coordinates come in pairs, one for the x-axis and one for the y-axis:

Example

<area shape=»poly» coords=»140,121,181,116,204,160,204,222,191,270,140,329,85,355,58,352,37,322,40,259,103,161,128,147″ href=»croissant.htm»>

This is the area that becomes clickable and will send the user to the page «croissant.htm»:

Новое решение:

это новый элемент, который является частью HTML5.

Он реализует способ описания адаптивных изображений таким же способом, как это делается в и . Таким образом можно размещать несколько тегов , каждый из которых содержит имена файлов различных изображений вместе с условиями, при которых те должны быть загружены.

Это позволит загружать разные изображения в зависимости от:

  • Результатов media выражений, например высоты, ширины или ориентации видимой области
  • Плотности пикселей

Это в свою очередь означает, что вы можете:

  • Загружать файлы изображений соответствующего размера, эффективно используя пропускную способность.
  • Загружать по-разному ориентированные изображения в разных пропорциях для того, чтобы соответствовать изменениям в макете при разных ширинах.
  • Загружать изображения с высоким разрешением для дисплеев с повышенной плотностью пикселей.

Использование разных изображений в зависимости от условий

More

Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsGet Iframe Elements

The HTML Element

The HTML element gives web developers more flexibility in specifying image resources.

The element contains one or more elements, each referring to different images through the attribute. This way the browser can choose the image that best fits the current view and/or device.

Each element has a attribute that defines when the image is the most suitable.

Example

Show different images for different screen sizes:

<picture>  <source media=»(min-width: 650px)» srcset=»img_food.jpg»>   <source media=»(min-width: 465px)» srcset=»img_car.jpg»>  <img src=»img_girl.jpg»></picture>

Note: Always specify an element as the last child element of the element. The element is used by browsers that do not support the element, or if none of the tags matches.

HTML Tutorial

HTML HOMEHTML IntroductionHTML EditorsHTML BasicHTML ElementsHTML AttributesHTML HeadingsHTML ParagraphsHTML StylesHTML FormattingHTML QuotationsHTML CommentsHTML Colors Colors RGB HEX HSL

HTML CSSHTML Links Links Link Colors Link Bookmarks

HTML Images Images Image Map Background Images The Picture Element

HTML TablesHTML Lists Lists Unordered Lists Ordered Lists Other Lists

HTML Block & InlineHTML ClassesHTML IdHTML IframesHTML JavaScriptHTML File PathsHTML HeadHTML LayoutHTML ResponsiveHTML ComputercodeHTML SemanticsHTML Style GuideHTML EntitiesHTML SymbolsHTML EmojisHTML CharsetHTML URL EncodeHTML vs. XHTML

Image Maps

The HTML tag defines an image map. An image map is an image with clickable areas. The areas are defined with one or more tags.

Try to click on the computer, phone, or the cup of coffee in the image below:

Example

Here is the HTML source code for the image map above:

<img src=»workplace.jpg» alt=»Workplace» usemap=»#workmap»><map name=»workmap»>  <area shape=»rect» coords=»34,44,270,350″ alt=»Computer» href=»computer.htm»>  <area shape=»rect» coords=»290,172,333,250″ alt=»Phone» href=»phone.htm»>  <area shape=»circle» coords=»337,300,44″ alt=»Coffee» href=»coffee.htm»></map>

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider


С этим читают