Note: How to use HTML "picture" for responsive images. Responsive Images

The easiest way to “adapt” an image is to set the width to 100% and calculate the height automatically. Our image will never be wider than the parent block, and the browser will resize it while maintaining its proportions. The disadvantage of this method is that both the mobile phone and the desktop are given the same large picture. It will be better if a smaller image is sent to the smartphone. This way we save traffic for the visitor and speed up page loading.

Tag Adaptive Images

Adaptive Images interesting solution given the ease of installation and the absence of problems with changing the markings. Determines the size of the visitor's screen and inserts the desired image onto the page.

There is nothing complicated about the installation. Download the distribution from http://adaptive-images.com/. Copy the adaptive-images.php and .htaccess files to the root of the site. Most likely there is already a .htaccess file in the root. In this case, edit it but make a copy first, just in case. If your .htaccess file has a section that starts with

  • paste into this section what is contained between #Adaptive-Images and #END Adaptive-Images. If there is no such section, then copy the entire contents.
    You need to insert the following JS code into the section

  • < script>document.cookie = "resolution=" + Math .max (screen.width , screen.height ) + "; path=/" ;
  • This code should load before other scripts.
    The last step is to configure the adaptive-images.php file. The $resolution variable specifies the width of the screens. As a rule, the dimensions specified in media queries in CSS are set. $cache_path is the path to the folder where the modified images will be stored.

    Now let's talk about how it all works. The size of the visitor window is determined by the JavaScript placed in the section. This information is recorded in cookies. When the browser encounters a tag on the page and sends a request to the server to get the image, it sends cookies. Apache web server Having received a request for an image, he looks to see if he has any special instructions for files. In .htaccess we have a rule according to which the server sends any request for jpg, png or gif to adaptive-images.php. PHP file looks for cookies and finds out what screen size it is. Next, the value from the cookie is compared with the values ​​​​prescribed in the $resolution variable and selected best value. Let's assume the value 480px was selected. The rendered image should be in the /ai-cashe/480/ folder. If it is not there, it will be requested source file and if its width is less than the width of the screen, then the visitor will be given the original file. If the size is larger, the file is reduced to the right size and is sent to the user. The modified copy is saved so as not to resize it next time.

    A couple more ways to make responsive images

    Browsing possible solutions I noticed that they were all offered before the element This new element offers best option solving the problem of adaptive images.

    Adaptive Image - easy to configure. This is a good alternative if you don’t want to bother with a bunch of files, creating three files for each image. Although this plus can turn into a minus. Often when reducing large photographs, it is ultimately better to cut out some part than to simply resize it. Another disadvantage of Adaptive Image is the load on the server.

    By the way, if your site runs on Drupal, in the next article we will try to implement and automate the process of resizing images as much as possible.

    • No description found for element 'yml_catalog'. The root element may be specified incorrectly.
    • The error is apparently due to the fact that the XML is not generated at all, or you provided Yandex with an incorrect link to YML. To find the cause of the error, open the link to your YML in a browser.

    • Fatal error: XML parsing error: Error parsing XML feed: Unknown tag: XML tag "b" (string...
    • Some error occurred during the YML generation process. PHP threw an error message, and it does this in the "b" tag. Open source code YML, by line number you can easily find PHP text errors. If you don't know what it means, search on Google. I am sure you will find recommendations for eliminating this error.

    • A required picture element is missing
    • According to Yandex.Market rules, an exported product must have at least one picture. Products without pictures are not exported. Check that in the module settings in the “Number of product images” field there is a number greater than zero. And check that the products in the store database have pictures.

    • XML specification error. Bring your price list in line with the technical requirements of the selected format...
    • The error is caused by the presence of extraneous tags in the YML export. This happens if you export something to the keywords tag. Yandex does not need this tag. Specify in the module settings "Take keywords tag from the field" = "Do not unload"

    • No required offers"s parameter
    • The error states that a required product offer parameter was not found in YML. For clothing, shoes and accessories, the color and size of the product must be present in YML. By the line where the error occurred, you can find out which product does not have the color and/or size specified. For this product in OpenCart you need to specify an attribute or option that will be exported by the module to YML. Check this attribute or option in the module settings.

    Errors that appear in the browser
    • Error 500 or 502" when opening YML in browser Bad Gateway", or just a white screen.
    • The script generating YML completed with an error. Your site settings are such that errors are not shown. You need to enable error display. Enabling errors in the store settings in the OpenCart admin will most likely not be enough. Error display must be enabled in the .htaccess and php.ini files. But this may not be enough. The site hosting may be configured in such a way that these files may not affect the error output. The best thing to do is to contact technical support hosting.

    • XML parsing error: root element not found
    • The script generating YML completed with an error. In this case, the YML was not completely formed - there are no closing tags. Take a look at the YML source code. If there is an error message at the end, look for the error text in Yandex or Google. If there is no error message, see the previous paragraph.

    • Error "Maximum execution time of 30 seconds exceeded"
    • By default, the PHP script is given 30 seconds to execute. If the script did not generate YML within 30 seconds, the script was forcibly terminated. Of course, YML was not formed, or was not fully formed.
      The fact is that exporting the entire commodity base is a rather resource-intensive operation. Scaling images for Yandex takes a particularly long time, because Yandex accepts images no smaller than 600x600 pixels in size. Luckily, OpenCart stores scaled images in an image cache. When exporting again, the images will be quickly taken from the cache. Until the image cache is fully formed, the YML export script may take a long time to complete. Try to run the script several times, a cache will be formed, the script will run faster, falling within the time limit.
      If this does not help, the YML generation time is still long (due to the fact that you have a lot of products), then you can try increasing the max_execution_time parameter in the file PHP settings php.ini.
      If this is not enough (your hosting is rather weak for an online store with such a product base), then you can try to generate YML export by running the script via php-cli.

      YML Content Questions
      • Not all goods are exported.
      • There may be several reasons why not all products are present in the YML export. The common reason is the module settings and the contents of the product database.

  • Products do not have a manufacturer specified, but in the settings tab of the “What to export” module, manufacturers are selected.
  • Products do not have main categories, but the “Products have main categories” checkbox is checked in the “General” tab.
  • The product is in the black list or not in the white list, which is specified on the “What to export” tab of the module settings.
  • The fields “Unload only if the goods are more expensive”, “Do not unload if the goods are more expensive” or the “Do not unload goods without pictures” checkbox in the “What to export” tab exclude the goods from those exported.
  • The product is out of stock, and its status is "Out of stock" such that the product is not exported. To export an out-of-stock item, in the “Warehouse and Delivery” tab of the module settings, do not select any status in the “Status Out of Stock” field.
  • Not all categories are included in exports.
  • In OpenCart, one product can be shown in several categories, but in YML format, a product can only belong to one category. The export module assigns the product to the first available category. Therefore, it may turn out that there are no goods in some categories, and these categories will not be present in exports, although goods will be present, albeit in other categories.
    ocStore has main categories, and you can only link products to main categories. To do this, in the module settings, check the box "Products have main categories." In this case, you will receive a more detailed classification of goods in YML export, but goods for which the main category is not specified will not be exported at all.

    How to make...?
    • How not to export a product that has zero quantity?
    • In the module settings, in the "Warehouse and delivery" tab, look for the "Status "Out of stock"" field. In this field, check All product statuses. To select multiple list items, hold down the Ctrl key while clicking with the mouse.

    Development in languages: PHP, JavaScript, node.js. Databases: MySQL, PostgreSQL, MongoDB.
    Improvement of CMS: OpenCart, PrestaShop, Wordpress. Integration with: payment systems, VKontakte, Facebook, Yandex.

    To create a smart banner, you need to add a feed - a file with information about products and services. Direct will analyze the content of the feed and automatically generate a smart banner with product offers for display on networks. You can use the feed loaded when creating dynamic ads.

    Types of businesses and feeds

    To load your feed, you need to select the type of business you are advertising.

    Feed type Business type Why
    Yandex.Market feed (XML) Retail Sale of electronics and accessories, household appliances, industrial equipment, clothing, furniture, gardening products, sporting goods, building materials, children's products, tires and wheels, cosmetics, perfumes, etc.
    Feed "Hotels and rental housing" Google Ads(CSV) Hotels Hotel reservations
    Auto.ru feed (XML) Cars Sale of new and used cars
    Yandex.Real Estate feed (XML) Real estate Sale of residential real estate
    Google Ads Flights Feed (CSV) Flights Airline ticket sales
    Universal feed (CSV) Other business Products and services not suitable for other types of business
    Yandex.Market feed (XML)
    Google Ads Custom Feed (CSV)
    Google Ads Travel Feed (CSV) Sale of tours, train tickets, ferries, etc.

    Product offers that are not described according to their type will be rejected.

    Feed requirements

    Any XML document can only contain one root element. The YML format uses the element as the root element. The element's date attribute must match the date and time the YML file was generated on the advertiser's side. The date must be in the format YYYY-MM-DD hh:mm.

    • Simplified description type
    • Custom description type (vendor.model)

    Basic, simpler type of description.

    Example: \n \n 1620.00\n 1800.00\n RUB\n 19\n \n false\n true\n false\n ESET Antivirus NOD32 Platinum Edition\n Eset\n NOD32-ENA-NS(BOX)-2-1\n Antivirus ESET NOD32 Platinum Edition - license for 2 years NOD32-ENA-NS(BOX)-2-1\n Payment: Cash, B/N, plastic cards, credit\n true\n Russia\n 18\n

    Element Attributes

    Elements included in

    Item Description
    name

    Name of the product offering. It is recommended to indicate the name and code of the manufacturer in the title of the simplified proposal.

    Required element.

    url

    Page URL goods.

    Required element.

    picture
    price
    currencyId
    model
    vendor

    Manufacturer.

    vendorCode
    description
    categoryId

    .

    market_category
    store
    pickup
    delivery
    oldprice
    sales_notes

    Order information:

    manufacturer_warranty

    Availability of guarantee:

    country_of_origin

    Country of origin of the product.

    adult
    age
    downloadable

    Possibility to download the product:

      true - the product can be downloaded;

      false - the product cannot be downloaded.

    This type of description is the most convenient and universal; it is recommended for describing products from most categories.

    Example: \nhttp://www.nadezhnayatekhnika.rf/catalog/element/index.php?from=ya_market&utm_source=ya_market&utm_medium=cpc& \n889.00 \n17000.00 \nRUR \n1111 \nhttp://89.123.45.678/catalog /photo/19/6.JPG \nfalse \nfalse \ntrue \nPrinter \nHP \nDeskjet D2663 \nA series of printers for people who need a reliable, easy-to-use color printer for everyday printing... \nPrepayment required. \ntrue \nJapan \n

    Element Attributes

    Attribute Description
    id

    Product ID.

    Required attribute.

    type

    Required attribute.

    available

    Possibility to buy goods:

    • true - product is in stock;
    • false - product is out of stock.
    Attribute Description
    id

    Product ID.

    Required attribute.

    type

    Offer description type. The value should be vendor.model .

    Required attribute.

    available

    Possibility to buy goods:

    • true - product is in stock;
    • false - product is out of stock.

    Elements included in

    Item Description
    url

    Product page URL.

    Required element.

    picture

    A must-have element for smart banners.

    price

    The price at which this product can be purchased.

    currencyId

    Currency code (RUB, USD, UAH, KZT).

    Required element if there is a price element.

    model

    Required element.

    vendor

    Manufacturer.

    Required element.

    vendorCode

    Product code (manufacturer code is indicated).

    description

    Description of the product offer.

    typePrefix
    categoryId

    Required element. An element can only contain one element.

    market_category
    store

    Possibility to buy goods in retail store:

      true - the product can be purchased in a retail store;

      false - there is no possibility of purchasing in a retail store.

    pickup

    Possibility of self-pickup from points of issue:

      true - the goods can be picked up yourself;

      false - there is no possibility of self-pickup.

    delivery

    Possibility of courier delivery of goods:

      true - courier delivery is possible;

      false - the product cannot be delivered by courier.

    oldprice

    The old price of a product, which must be higher than the new price.

    sales_notes

    Order information:

      minimum amount order, minimum quantity of goods, the need for prepayment;

      payment options, descriptions of promotions and sales.

    manufacturer_warranty

    Availability of guarantee:

      true - the product has an official guarantee;

      false - the product does not have an official guarantee.

    country_of_origin

    Country of origin of the product.

    adult
    age
    downloadable

    Possibility to download the product:

      true - the product can be downloaded;

      false - the product cannot be downloaded.

    Hotels: Google Ads Hotels & Rentals feed

    The Google Ads Hotels & Rentals CSV feed must be used for the Hotels business type. The first line contains the column names, and following lines- the data itself. The contents of the columns are separated by a comma. Data in the feed must be in UTF-8 encoding.

    Item Description

    Hotel ID.

    Required element.

    Hotel name.

    Required element.

    Offer page URL.

    Required element.

    Destination name

    Required element.

    A must-have element for smart banners.

    Price
    Item Description

    Hotel ID.

    Required element.

    Hotel name.

    Required element.

    Offer page URL.

    Required element.

    Destination name

    Hotel location (max. 25 characters).

    Required element.

    A must-have element for smart banners.

    Price

    Offer price. Number and currency code (RUB, USD, UAH, KZT). Use a period (.) as a decimal separator.

    Number of stars. An integer from 1 to 5.

    User rating, number. Use a period (.) as a decimal separator.

    Maximum possible score, integer. Default is 5.

    Hotel services. Specify the values ​​separated by semicolons: bar;pool;free Wi-Fi

    Note. Values ​​containing a comma must be enclosed in quotation marks (\"\"). For example, \"Moscow, center\".

    Cars: feed Auto.ru

    Auto.ru feed in XML format must be used for the Automotive business type. Data in the feed must be in UTF-8 encoding.

    A list of advertiser's real estate offers for sale is contained in the element. Each product offering (apartment) is described by a separate element.

    In one feed you can transmit information about different residential complexes from different developers. To do this, indicate in each legal information about the developer in the element.

    Attention.

    We do not accept rental property feeds.

    Example: \n sale\n residential\n apartment\n http://www.developer.ru/search18\n 2015-04-02T19:00:06+03:00\n \n St. Petersburg\n o. Vasilievsky\n 18th line V.O., 32\n \n Vasileostrovskaya\n 10\n 5\n \n \n \n 4780000\n RUR\n \n \n JSC \"Developer\" \n \n 13\n 15\n \n 63.00\n sq. m\n \n Northern Fantasy\n http://www.developer.ru/images/plans/000001289.jpg\n

    Element Attributes

    Elements included in

    The table below describes the feed elements that are used to create smart banners or dynamic ads.

    Item Description
    type

    Transaction type.

    The meaning is only sale.

    Required element.

    location

    \n \n \n \n …\n

    Required element.

    locality-name

    Name of the locality.

    Required element.

    sub-locality-name
    address
    metro

    Nearest metro station.

    \n \n \n \n

    name
    time-on-transport
    time-on-foot
    url

    Required element.

    image

    A must-have element for smart banners.

    building-name

    Required element.

    sales agent

    \n \n

    Required element.

    organization

    Required element.

    price

    \n \n \n

    value
    currency

    Currency code (RUB, USD, UAH, KZT).

    area

    Total area.

    \n \n \n

    value
    unit

    Unit of room area.

    floor
    Item Description
    type

    Transaction type.

    The meaning is only sale.

    Required element.

    location

    A set of elements that describe the location of an object. Nested tags provide detailed information about the object's address.

    \n \n \n \n …\n

    Required element.

    locality-name

    Name of the locality.

    Required element.

    sub-locality-name
    address
    metro

    Nearest metro station.

    If there are several stations, each must be indicated in separate element. The nested tags indicate detailed information.

    \n \n \n \n

    name
    time-on-transport

    Time to the metro in minutes by transport.

    time-on-foot
    url

    Required element.

    image

    A must-have element for smart banners.

    building-name

    Name of the residential complex. Based on this element, apartments are combined into residential complexes.

    If the name of the residential complex is unknown, indicate the street and house number (Lenina, 25)

    Required element.

    sales agent

    Information about the developer. The nested tags provide detailed information:

    \n \n

    Required element.

    organization

    Name legal entity developer.

    Required element.

    price

    A set of elements describing the value of an object. The nested tags indicate the price and the currency in which the cost is indicated:

    \n \n \n

    value
    currency

    Currency code (RUB, USD, UAH, KZT).

    Required if there is a value element.

    area

    Total area.

    The value and unit of measurement of the area are transmitted in nested tags:

    \n \n \n

    value
    unit

    Unit of room area.

    The element is used if the price is specified per unit area.

    Possible values: sq. m/sq. m.

    floor

    Flights: Google Ads Flights feed

    The Google Ads Airline Tickets CSV feed must be used for the Airline Tickets business type. The first line contains the names of the columns, and the next lines contain the data itself. The contents of the columns are separated by a comma. Data in the feed must be in UTF-8 encoding.

    Example: Elements included in CSV

    The table below describes the feed elements that are used to create smart banners or dynamic ads.

    Item Description

    Required element.

    Destination name

    Destination name.

    Required element.

    e-commerce

    Name of departure point.

    Offer page URL.

    Required element.

    A must-have element for smart banners.

    Flight price

    Offer price. Number and currency code (RUB, USD, UAH, KZT). Use a period (.) as a decimal separator.

    Item Description

    Destination ID.

    Required element.

    Destination name

    Destination name.

    Required element.

    Origin ID.

    If you indicate Origin ID in the feed and have connected e-commerce in Yandex.Metrica, use Origin ID and Destination ID separated by a hyphen as the offer identifier in the Ecommerce object. For example, \"id\": \"VKO-LHR\" .

    Name of departure point.

    Offer page URL.

    Required element.

    A must-have element for smart banners.

    Flight price

    Offer price. Number and currency code (RUB, USD, UAH, KZT). Use a period (.) as a decimal separator.

    Other business: universal feed

    A universal feed in CSV format can be used in the Other Business type. The first line contains the column names, and the next lines contain the data itself. The contents of the columns are separated by a comma. Data in the feed must be in UTF-8 encoding.

    Elements included in CSV

    Item Description Description

    Offer ID.

    Required element.

    e-commerce

    Offer page URL.

    Required element.

    A must-have element for smart banners.

    Title Name of the offer.
    Description

    Description of the offer.

    Currency Offer ID.

    Required element.

    Second offer ID.

    If you indicate ID2 in the feed and have connected e-commerce in Yandex.Metrica, use ID and ID2 separated by a hyphen as the offer identifier in the Ecommerce object. For example, \"id\": \"VKO-LHR\" .

    Offer page URL.

    Required element.

    A must-have element for smart banners.

    Title Name of the offer.
    Description

    Description of the offer.

    Offer price without currency. Use a period (.) as a decimal separator.

    Currency

    Currency code (RUB, USD, UAH, KZT).

    Required if there is a Price element.

    The old offer price, which must be higher than the new price (Price).

    Offer ID.

    Required element.

    Second offer ID.

    If you indicate ID2 in the feed and have connected e-commerce in Yandex.Metrica, use ID and ID2 separated by a hyphen as the offer identifier in the Ecommerce object. For example, \"id\": \"VKO-LHR\" .

    Offer page URL.

    Required element.

    A must-have element for smart banners.

    Item title

    Name of the offer.

    Item description

    Description of the offer.

    In Yandex.Metrica, use ID and ID2 separated by a hyphen as the offer identifier in the Ecommerce object. For example, \"id\": \"VKO-LHR\" .

    Offer page URL.

    Required element.

    A must-have element for smart banners.

    Item title

    Name of the offer.

    Item description

    Description of the offer.

    Offer price with currency code in ISO 4217 encoding (RUB, USD, UAH, KZT). Use a period (.) as a decimal separator.

    New price proposals, which must be lower old price(Price).

    Other Business: Google Ads Travel Feed

    The Google Ads Travel CSV feed can be used in the Other Business type. The first line contains the column names, and the next lines contain the data itself. The contents of the columns are separated by a comma. Data in the feed must be in UTF-8 encoding.

    Elements included in CSV

    The table below describes the feed elements that are used to create smart banners.

    Item Description

    Destination ID.

    Required element.

    Destination name

    Destination name.

    Origin ID.

    If you indicate Origin ID in your feed and have enabled e-commerce

    Name of departure point.

    Offer page URL.

    Required element.

    A must-have element for smart banners.

    Name of the offer.

    Destination ID.

    Required element.

    Destination name

    Destination name.

    Origin ID.

    If you indicate Origin ID in the feed and have connected e-commerce in Yandex.Metrica, use Origin ID and Destination ID separated by a hyphen as the offer identifier in the Ecommerce object. For example, \"id\": \"MOS-AMS\" .

    Name of departure point.

    Offer page URL.

    Required element.

    A must-have element for smart banners.

    Name of the offer.

    Offer price with currency code in ISO 4217 encoding (RUB, USD, UAH, KZT). Use a period (.) as a decimal separator.

    New offer price, which must be lower than the old price (Price).

    Adding a feed

    To add a feed, on the campaign list page, follow the Feeds link. On the Manage Feeds page, click the +Add Feed button and select your business type.

    • File link
    • Upload file

    Select the file you need to upload. The size of the uploaded file should not exceed 512 MB. When updating, the file is downloaded by the robot, and the new data is imported into Direct.

    You can place your feed in an archive created using the algorithm ZIP compression(extension.zip) or GNU ZIP (extension.gz).

    If there was an error adding a feed (for example, the feed size, format, or link is not appropriate), you'll see an "Upload Error" status and a link to an error report.

    File Validation

    When reading a file, the following conditions are checked:

    • all required elements are present;
    • all element names are correct;
    • Each element appears at most once.

    If any of these conditions are not met, the file is rejected.

    Images have long been known to be the most time-consuming aspects of responsive web design. Today, we will see how we can use the picture element as a solution to the problem. adaptive images right now.

    Firstly, the problem itself

    The days of fixed-width website design with full layout compliance are long gone. In today's time of widescreen monitors, Internet television, tablets and smartphones various sizes our design must take into account any resolution - from 320 pixels to 7680.

    All of these resolutions place demands on images - they must stretch and shrink to accommodate a variety of requirements. This may be a problem because... except vector graphics, most images have a fixed pixel width that does not change.

    So what to do?

    The current, most common solution

    Typically, you will find the following in the CSS code of almost any responsive website:

    img (max-width: 100%; height: auto;)

    img (max - width: 100%; height: auto;)

    This code uses the max-width setting: 100%; to make sure that the image will not extend beyond the parent container. If the parent container becomes smaller than the width of the image, the image will shrink along with it. Setting height: auto; is present so that when reduced, the proportions of the image are maintained.

    One rubber image for all devices

    This solves the problem in one key, allowing us to show one image per different circumstances. But, it doesn't allow us to show different images for different circumstances.

    New solution: picture tag

    picture is a new element that should be part of HTML5. It will significantly speed up the process of placing adaptive images, similar to the principles of operation of the audio and video elements. It will allow you to specify multiple source elements, each of which will point to various files images along with the conditions under which they must be loaded.

    It will allow you to download various images depending on:

    Media query results, such as viewport height, width, orientation

    Pixel Density

    Which means you can:

    Upload images of appropriate sizes, making maximum use of the available channel width.

    Upload images with different cropping and aspect ratios to accommodate changing layouts for different screen widths.

    Upload images from high resolution for screens with high pixel density.

    Various images loaded depending on the circumstances

    How does the picture element work?

    The basic steps for working with the picture element are:

    Creating opening and closing picture tags.

    Within these tags, create a source element for each request you want to make.

    Add a media attribute to your query for things like viewport height, width, orientation, etc.

    Add a srcset attribute with the appropriate name of the image file to upload.

    Add additional filenames to your srcset attribute if you want to support high pixel density screens such as Retina.

    Add an img element as a fallback.

    Here's a simple example that checks if the viewport is smaller than 768 pixels, and if it does, loads a smaller image:

    < picture > < source srcset = "smaller.jpg" media = "(max-width: 768px)" > < source srcset = "default.jpg" > < img srcset = "default.jpg" alt = "My default image" > < / picture >

    You'll notice that the syntax used in the media attribute is exactly the same as what you're used to when writing CSS media queries. You can use the same checks, meaning you can create queries for max-width, min-width, max-height, min-height, orientation, and so on.

    You can use these checks to load landscape or portrait versions of an image depending on the device's orientation, and you can also add size queries. For example:

    < picture > < source srcset = "smaller_landscape.jpg" media = "(max-width: 40em) and (orientation: landscape)" > < source srcset = "smaller_portrait.jpg" media = "(max-width: 40em) and (orientation: portrait)" > < source srcset = "default_landscape.jpg" media = "(min-width: 40em) and (orientation: landscape)" > < source srcset = "default_portrait.jpg" media = "(min-width: 40em) and (orientation: portrait)" > < img srcset = "default_landscape.jpg" alt = "My default image" > < / picture >

    The code above loads a smaller, landscape-cropped version of the image for the device with the appropriate orientation. It loads a larger version of the same image for larger screen devices.

    If the device is in portrait orientation, it downloads the image cropped accordingly: at a smaller size - for small devices and a larger image for higher resolution devices.

    If you want to provide versions of images with different resolutions For higher density screens, you can do this by adding additional filenames to the srcset attribute. For example, let's look at the first code example above with the addition of Retina 2x screen resolution support:

    < picture > < source srcset = "smaller.jpg, smaller_retina.jpg 2x" media = "(max-width: 768px)" > < source srcset = > < img srcset = "default.jpg, default_retina.jpg 2x" alt = "My default image" > < / picture >

    The media request is processed first, so you can control the size of the image on the screen. Next, the pixel density of the screen is checked and if high density is supported and allowed by the user settings, a higher resolution version of the image will be loaded.

    Using picture today

    Currently, a native implementation of picture is in development for Chrome, Firefox and Opera browsers. In the future, we will most likely see wider support in other browsers. But, as of today, support is only expected.

    For now, you don't have to wait if you want to start using picture right now. You just need to use Picturefill 2.0, a polyfill provided by the developers at Filament Group.

    Once you download the picturefill.js file into your project, it can be used simply by loading it into the head section of your site:

    It is also possible to load the script asynchronously for greater efficiency, which you can read about in the Picturefill documentation. Together with loading this script, the picture element will work as I described, with minor restrictions. ] -- >< source srcset = "smaller.jpg" media = "(max-width: 768px)" > < source srcset = "default.jpg" > < ! -- [ if IE 9 ] > < / video > < ! [ endif ] -- > < img srcset = "default.jpg" alt = "My default image" > < / picture >

    Android 2.3

    Just like IE9, Android 2.3 does not see source elements inside picture tags. However, it recognizes the srcset attribute when it is assigned to a regular img tag. Make sure you include a fallback img element with the default filename in the srcset attribute for Android 2.3 or any other browser with a similar problem.

    Requires JavaScript and native media query support

    Since this solution is implemented in JavaScript, it therefore needs JavaScript to correct operation in the browser. Picturefill 2.0 does not provide solutions for “no-js” because otherwise, a lot of images would appear on pages when native support is implemented. However, you can use Picturefill 1.2 if the “no-js” feature is important to you.

    The next requirement of Picturefill is native support for media queries in order for queries in the media attribute to work. All modern browsers support media queries, while IE8 and below is the only browser that does not support it, with a small residual user base.

    Possible additional HTTP requests

    For browsers that have native srcset support but do not support picture, it is possible given name file in a fallback img element may be requested before a more suitable image has been defined in the img element. This problem is temporary and will be resolved when native picture support is implemented.

    In the development builds of the Chrome, Firefox and Opera browsers, support for the new picture element has appeared, designed to solve a number of problems arising during development adaptive designs. Let's take a closer look at it.

    The new picture element solves the following problems facing the developer responsive web applications(I'll use the classification proposed by pepelsbey at one of the recent frontend conferences):

  • R retina, i.e. screens with a dpi density of 150 or higher, on which normal images appear blurry
  • And responsiveness is the task of resizing the image according to your rules written in the design depending on the size of the viewport.
  • Format, ability to use modern formats such as WebP if they are supported by the browser
  • To framing or artistic purposes. Cropping of unimportant parts of the image when displayed on devices with smaller screens.
  • Adding the first letters, we get the mnemonic RAFC Syntax Conventionally, the extended syntax of the new element looks like this
    ...
    The picture element does not render any content, but is merely a reference container for what is nested within it. img tag.

    Therefore, for most tasks, the abbreviated notation will suffice, without using picture at all

    Let's look at how the above problems are solved using a new element. All example files can be found in this repository github.com/fetis/picture

    To test the examples in this article on the desktop, you will need either Firefox Nighlty (picture support is enabled by setting dom.image.picture.enable in about:config) or Chrome Canary, or Opera Developer. On mobile device the new element can be tested in Chrome Beta

    Retina We have a 400x300 px image that we want to also display beautifully at double and triple pixel density. To do this, prepare 2 more pictures, sizes 800x600 and 1200x900, and write the following code

    2x and 3x is pixel density descriptors, they tell the browser that these images were prepared for this density, if you want, you can use it. Please note that they do not force the browser to use these images, but only prompt it. The final decision rests with him depending on other conditions, such as the current connection.

    The src attribute in in this case serves as a source of images for density< 2 и фолбеком на случай, если браузер не поддерживает новый элемент.

    Adaptability Let's imagine a layout in which there is a single breakpoint of 700 px. When the viewport size is more than 700 px, we show a sidebar on the right and the size of our image should be 75% of the screen width. Otherwise, the sidebar is located at the end of the page and the image should be stretched to the full width. This is implemented by the following code

    400w, 800w, 1200w - these are the width descriptors, they tell the browser what width the image is located at a given URL and, based on this information, the browser decides which image is best suited in current situation. As in the case of retina, the information is advisory in nature and the final decision on which image to load remains with the browser.

    The simultaneous use of density and width descriptors is not allowed.

    The sizes attribute lists the image sizes for all the control points in our design. Breakpoints are set in the form of a regular media expression, the browser takes the first one, which returns True and does not consider the chain further. The width value uses the new length unit vw , which returns a value as a percentage of the viewport width.

    If there is no need for a picture to use control points, then the entry can be shortened to this sizes="100vw" . And for more complex designs you can use the CSS calc() function, for example
    sizes="(max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"

    The most difficult attribute to behave in my opinion. If you do not specify sizes , then the browser always chooses the most big picture. In combination with width it does not work, although it would seem a logical combination and a number of other glitches. Perhaps these are features of early implementation.

    As you can see, we have already covered 80% of the needs adaptive layout, and have never used picture before, it’s time for it to come into play too.

    Format Use various formats for images differs little from the methods used for video or audio tags

    We specify a list of sources and mime/type for each, and the browser already selects the first one that it knows. The image from the src attribute is used as a fallback. Cropping When we show a photo on a smaller screen, sometimes it makes sense to trim off unnecessary details, leaving only the main part. The media attribute will help us cope with this task.

    In each media attribute we specify a media expression, in which the original image will change and, unlike previous examples, the browser will obliged follow him. Also note how cropping is combined here with adaptability to stretch the image to its full width. RAFC And now all 4 methods in one bottle :) Perhaps this is what inserting pictures will look like in a couple of years (example from the Opera blog)

    2 are used here JPEG format and WebP. When the screen width is more than 1280 px, a full-size image is shown in half the viewport. With a width from 640 to 1279, a cropped photo is shown at 60% of the viewport width. When the screen width is less than 640px, the cropped photo is shown at 100% width. Select according to current Screen DPI produced based on the width of the source files.