- Как сделать изображения адаптивными с помощью CSS
- How to Resize Images Proportionally for Responsive Web Design With CSS
- Resize images with the HTML width and height attributes
- Example of resizing an image proportionally with the width and height attributes:
- Result
- Resize images with the CSS width and height properties
- Example of resizing an image proportionally with the width and height properties:
- Resize images with the CSS max-width property
- Example of adding a responsive resized image with the max-width property:
- Example of resizing an image proportionally using the max-width property:
- How TO — Responsive Images
- How To Create Responsive Images
- Example
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Как сделать изображения адаптивными с помощью 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 Resize Images Proportionally for Responsive Web Design With CSS
One of the main parts of responsive web design is resizing the image automatically to fit the width of its container. Since nowadays people use different kinds of desktops, our web pages must be appropriate for all types of screens.
So, let’s learn three ways of resizing images and making responsive images with only HTML and CSS.
Resize images with the HTML width and height attributes
Example of resizing an image proportionally with the width and height attributes:
html> html> head> title>Title of the document title> head> body> p>Resized image: p> img src="/uploads/media/default/0001/01/25acddb3da54207bc6beb5838f65f022feaa81d7.jpeg" alt="Aleq" width="160" height="145" /> p>Original image size: p> img src="/uploads/media/default/0001/01/25acddb3da54207bc6beb5838f65f022feaa81d7.jpeg" alt="Aleq" /> body> html>
Result
While resizing an image, the aspect ratio (the viewable area and display shape) should be preserved. Otherwise, the image can get distorted and lose its quality.
Resize images with the CSS width and height properties
Another way of resizing images is using the CSS width and height properties. Set the width property to a percentage value and the height to «auto». The image is going to be responsive (it will scale up and down).
Example of resizing an image proportionally with the width and height properties:
html> html> head> title>Responsive Resized Image title> style> img < width: 100%; height: auto; > style> head> body> h2>Responsive Resized Image h2> p>Resize the browser to see the responsive effect: p> img src="/uploads/media/default/0001/03/5bfad15a7fd24d448a48605baf52655a5bbe5a71.jpeg" alt="New York" /> body> html>
Note that the image could be scaled more than the original size. In several cases, a better option is to use the max-width property alternatively.
Resize images with the CSS max-width property
There is a better way for resizing images responsively. 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. The trick is to use height: auto; to override any already present height attribute on the image.
Example of adding a responsive resized image with the max-width property:
html> html> head> title>Responsive Resized Image with max-width title> style> img < max-width: 100%; height: auto; > style> head> body> h2>Responsive Resized Image with max-width h2> p>Resize the browser to see the responsive effect: p> img src="/uploads/media/default/0001/03/5bfad15a7fd24d448a48605baf52655a5bbe5a71.jpeg" alt="New York" /> body> html>
Let’s see another live web page example with the same method.
Example of resizing an image proportionally using the max-width property:
html> html> head> title>Responsive Resized Image in a Web Page title> style> * < box-sizing: border-box; > html < font-family: "Lucida Sans", sans-serif; > img < width: 100%; height: auto; > .row:after < content: ""; clear: both; display: table; > .menu, .content < float: left; padding: 15px; width: 100%; > @media only screen and (min-width: 600px) < .menu < width: 25%; > .content < width: 75%; > > @media only screen and (min-width: 768px) < .menu < width: 20%; > .content < width: 79%; > > .header < background-color: #1c87c9; color: #ffffff; padding: 10px; text-align: center; > .menu ul < list-style-type: none; margin: 0; padding: 0; > .menu li < padding: 8px; margin-bottom: 7px; background-color: #666666; color: #ffffff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); > .menu li:hover < background-color: #1c87c9; > .footer < background-color: #1c87c9; color: #ffffff; text-align: center; font-size: 12px; padding: 15px; > style> head> body> div class="header"> h1>W3DOCS h1> div> div class="row"> div class="menu"> ul> li>Books li> li>Snippets li> li>Quizzes li> li>Tools li> ul> div> div class="content"> h2>About Us h2> p> W3docs provides free learning materials for programming languages like HTML, CSS, Java Script, PHP etc. p> p> It was founded in 2012 and has been increasingly gaining popularity and spreading among both beginners and professionals who want to enhance their programming skills. p> img src="/uploads/media/default/0001/02/8070c999efd1a155ad843379a5508d16f544aeaf.jpeg" alt="Team Work" /> div> div> div class="footer"> p> Resize the browser window to see how the content respond to the resizing. p> div> body> html>
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.