- Как сделать изображения адаптивными с помощью CSS
- How TO — Responsive Images
- How To Create Responsive Images
- Example
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Responsive Web Design — Images
- Using The width Property
- Example
- Using The max-width Property
- Example
- Add an Image to The Example Web Page
- Example
- Background Images
- Example
- Example
- Example
- Different Images for Different Devices
- Example
- Example
- The HTML Element
- Example
Как сделать изображения адаптивными с помощью CSS
Большинство сегодняшних сайтов адаптивны. А если в нём нужно центрировать и выровнять изображение, необходимо научиться делать изображения плавными или адаптивными с помощью CSS.
Пару недель назад я опубликовал обучающее видео, в котором объяснил, как сделать адаптивный веб-сайт. В видео мы сделали изображение адаптивным. В этом посте я хотел бы рассказать об этом подробнее.
Также вы узнаете некоторые общие проблемы, которые могут возникнуть при попытке сделать изображения адаптивными. Я постараюсь объяснить, как их решить.
Сделать изображение гибким или отзывчивым на самом деле довольно просто. Когда вы загружаете изображение на веб-сайт, оно имеет ширину и высоту по умолчанию. Вы можете изменить их с помощью CSS.
Чтобы изображение было отзывчивым, нужно присвоить новое значение его свойству width. Тогда высота изображения автоматически изменится.
Важно знать, что вы всегда должны использовать относительные единицы для свойства ширины, такие как процент, а не абсолютные единицы, такие как пиксели.
Например, если вы определите фиксированную ширину 500 пикселей, ваше изображение не будет отзывчивым, потому что единица измерения абсолютная.
Вот почему вам следует вместо этого назначить относительную единицу, например 50%. Такой подход сделает ваши изображения плавными, и они смогут изменять свой размер независимо от размера экрана.
Один из вопросов, который мне задают чаще всего, — следует ли использовать медиа-запросы.
Медиа-запрос — еще одна важная функция CSS, которая помогает сделать веб-сайт адаптивным. Я не буду вдаваться в подробности, но вы можете прочитать другой мой пост позже, чтобы узнать, как использовать медиа-запросы более подробно.
Ответ на этот вопрос: «это зависит от обстоятельств». Если хотите, чтобы изображение имело разные размеры от одного устройства к другому, нужно будет использовать медиа-запросы. В противном случае вы этого не сделаете.
Теперь для этого примера ваше изображение имеет ширину 50% для любого экрана. Но если вы хотите сделать его полноразмерным для мобильных устройств, понадобится помощь медиа-запросов:
Таким образом, в соответствии с правилом медиа-запроса любое устройство размером менее 480 пикселей будет занимать всю ширину экрана.
Другой способ, которым разработчики могут создавать адаптивные изображения, — это свойство max-width. Однако это не всегда лучший метод, поскольку он может работать не для всех размеров экрана и устройств.
Прежде чем перейти к примеру, необходимо понять, что именно делает свойство max-width.
Свойство max-width устанавливает максимальную ширину для элемента, которая не позволяет ширине этого элемента быть больше, чем его значение max-width (но может быть меньше).
Например, если изображение имеет ширину по умолчанию 500 пикселей, а размер вашего экрана всего 360 пикселей, вы не сможете увидеть полное изображение, потому что недостаточно места:
Поэтому вы можете определить свойство max-width для изображения и установить его на 100%, что сжимает изображение с 500 до 360 пикселей. Таким образом, вы сможете увидеть полное изображение на экране меньшего размера.
Хорошо то, что, поскольку вы используете относительные единицы, изображение будет плавным на любом устройстве размером менее 500 пикселей.
К сожалению, размер экрана будет несколько больше 500 пикселей, но изображение не изменится, поскольку его ширина по умолчанию составляет 500 пикселей. Такой подход нарушит отзывчивость изображения.
Чтобы исправить это, вам нужно снова использовать свойство width, что делает бесполезным свойство max-width.
Другая распространенная проблема, с которой вы можете столкнуться, связана со свойством высоты. Обычно высота изображения автоматически изменяется, поэтому вам не нужно назначать свойство высоты вашим изображениям (потому что это как бы ломает изображение).
Но в некоторых случаях вам, возможно, придется работать с изображениями, которые должны иметь фиксированную высоту. Поэтому, когда вы назначаете фиксированную высоту изображения, оно все равно будет отзывчивым, но не будет хорошо выглядеть.
How TO — Responsive Images
Responsive images will automatically adjust to fit the size of the screen.
Resize the browser window to see the responsive effect:
How To Create Responsive Images
Step 1) Add HTML:
Example
Step 2) Add CSS:
If you want the image to scale both up and down on responsiveness, set the CSS width property to 100% and height to auto:
Example
If you want an image to scale down if it has to, but never scale up to be larger than its original size, use max-width: 100% :
Example
If you want to restrict a responsive image to a maximum size, use the max-width property, with a pixel value of your choice:
Example
Go to our CSS Images Tutorial to learn more about how to style images.
Go to our CSS RWD Tutorial to learn more about responsive web design.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Responsive Web Design — Images
Resize the browser window to see how the image scales to fit the page.
Using The width Property
If the width property is set to a percentage and the height property is set to «auto», the image will be responsive and scale up and down:
Example
Notice that in the example above, the image can be scaled up to be larger than its original size. A better solution, in many cases, will be to use the max-width property instead.
Using The max-width Property
If the max-width property is set to 100%, the image will scale down if it has to, but never scale up to be larger than its original size:
Example
Add an Image to The Example Web Page
Example
Background Images
Background images can also respond to resizing and scaling.
Here we will show three different methods:
1. If the background-size 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):
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 background-size property is set to «100% 100%», the background image will stretch to cover the entire content area:
Example
div <
width: 100%;
height: 400px;
background-image: url(‘img_flowers.jpg’);
background-size: 100% 100%;
border: 1px solid red;
>
3. If the background-size 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:
Example
div <
width: 100%;
height: 400px;
background-image: url(‘img_flowers.jpg’);
background-size: cover;
border: 1px solid red;
>
Different Images for Different Devices
A large image can be perfect on a big computer screen, but useless on a small device. Why load a large image when you have to scale it down anyway? To reduce the load, or for any other reasons, you can use media queries to display different images on different devices.
Here is one large image and one smaller image that will be displayed on different devices:
Example
/* For width smaller than 400px: */
body background-image: url(‘img_smallflower.jpg’);
>
/* For width 400px and larger: */
@media only screen and (min-width: 400px) body <
background-image: url(‘img_flowers.jpg’);
>
>
You can use the media query min-device-width , instead of min-width , which checks the device width, instead of the browser width. Then the image will not change when you resize the browser window:
Example
/* For devices smaller than 400px: */
body background-image: url(‘img_smallflower.jpg’);
>
/* For devices 400px and larger: */
@media only screen and (min-device-width: 400px) body <
background-image: url(‘img_flowers.jpg’);
>
>
The HTML Element
The HTML element gives web developers more flexibility in specifying image resources.
The most common use of the element will be for images used in responsive designs. Instead of having one image that is scaled up or down based on the viewport width, multiple images can be designed to more nicely fill the browser viewport.
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
The srcset attribute is required, and defines the source of the image.
The media 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.