Как растянуть картинку на весь экран css?

Лучший способ растянуть изображение — это использовать свойство CSS3 background. Вот пример, который использует фоновое изображение для body страницы, рисунок всегда растянется и заполнит весь экран.

Чтобы растянуть картинку на весь экран с помощью CSS, вы можете использовать следующий код:
Этот код устанавливает ширину и высоту картинки равными 100%, что означает, что она будет занимать всю доступную ширину и высоту родительского элемента.
Обратите внимание, что этот код работает только если родительский элемент имеет определенную ширину и высоту. Если это не так, то вы можете использовать следующий код:
Этот код устанавливает ширину и высоту html и body равными 100%, а также убирает верхний и левый отступы (margin), чтобы картинка занимала все доступное пространство.
В этом случае картинка будет растягиваться или уменьшаться в размерах, чтобы соответствовать размерам родительского элемента. Если же вы хотите, чтобы картинка оставалась пропорциональной, но занимала все доступное пространство, можно сделать так:
Этот код устанавливает атрибут object-fit равным cover , что означает, что картинка будет обрезана, чтобы полностью заполнить доступное пространство, но при этом оставаться пропорциональной.
Нужно понимать, что этот код работает только в современных браузерах, поддерживающих атрибут object-fit . Если вы хотите, чтобы ваш код работал во всех браузерах, вы можете использовать JavaScript для реализации такого поведения.
Помогите сделать body на весь экран
Ребят делаю сайт, попросил друг, 3 года как не занимался этим, забросил, и очень многое забыл, сложно делать по старой памяти, но приходиться. Я делаю сайт на подобии того что делал раньше, но у меня видимо очень много ошибок, одна из их не могу понять почему body только закрывает часть сайта, а не на весь, уже больше 2 часов промучился переискал кучу инфы в интернете ничего не помогает, если вы не поможете прийдёться забросить это дело.
я всё проверял все галочки всё закрыто, не должно быть ошибок, но боди хоть убей закрывает часть только сайта из за этого едит весь блок

Ссылка на комментарий
Поделиться на других сайтах
3 ответа на этот вопрос
- Сортировать по голосам
- Сортировать по дате
Рекомендованные сообщения
Присоединяйтесь к обсуждению
Вы можете опубликовать сообщение сейчас, а зарегистрироваться позже. Если у вас есть аккаунт, войдите в него для написания от своего имени.
Примечание: вашему сообщению потребуется утверждение модератора, прежде чем оно станет доступным.
Похожие публикации
Добрый день! помогите пожалуйста со скриптом таймера(счетчика) тип времени работы компании. Требуют, чтобы было с годом, месяцем, днем, часами и т.д. Прошарил все сайты, не могу найти — сделать, чтобы он он шел вперед. ПРИМЕР: «мы на рынке уже: 7 лет, 2 месяца, 3 дня, 4 часа, 2 минуты, 33 секунды»
Напишите код, если не тяжело. Спасибо.
Для блока пытаюсь установить фон, при увеличении фон обрезается браузером до размера окна, но контент за его пределами имеется и остается без фона. что я делаю не так?
Здравствуйте прошу помочь реализовать нормальный слайдер, в данный момент все в принципи работает как и было задумано, но все картинки привязаны позиционно и накладываются друг на друга из-за чего при уменьшении размера все сбивается
<h3 color=»#63308a» >Личные качества</h3> <img align=»left» style=»margin-right: 30px;» src=»http://www.mqsart.ru/wp-content/uploads/2013/10/workroom_start-300×268.png» alt=»» width=»300″ height=»268″/> <a href=»javascript:void(0)»><img align=»left» style=»width:18px; height:18px; margin-right: 10px; margin-top: 2px;» src=»https://htmlforum.dev/topic/58626-pomogite-sdelat-body-na-ves-ekran/wp-content/themes/magnetto/layout/images/bg_level2_marker.png» alt=»»/><p><b>Ответственность</b></p><span><img align=»left» style=»margin-bottom: 99px;» src=»http://www.mqsart.ru/wp-content/uploads/2017/01/workroom_liability.png» alt=»» width=»300″ height=»268″/></span></a></br> <a href=»javascript:void(0)»><img align=»left» style=»width:18px; height:18px; margin-right: 10px; margin-top: 2px;» src=»https://htmlforum.dev/topic/58626-pomogite-sdelat-body-na-ves-ekran/wp-content/themes/magnetto/layout/images/bg_level2_marker.png» alt=»»/><p><b>Креативность</b></p><span><img align=»left» style=»margin-bottom: 99px;» src=»http://www.mqsart.ru/wp-content/uploads/2017/01/workroom_creative.png» alt=»» width=»300″ height=»268″/></span></a></br> <a href=»javascript:void(0)»><img align=»left» style=»width:18px; height:18px; margin-right: 10px; margin-top: 2px;» src=»https://htmlforum.dev/topic/58626-pomogite-sdelat-body-na-ves-ekran/wp-content/themes/magnetto/layout/images/bg_level2_marker.png» alt=»»/><p><b>Гибкость мышления</b></p><span><img align=»left» style=»margin-bottom: 99px;» src=»http://www.mqsart.ru/wp-content/uploads/2017/01/workroom_thinking.png» alt=»» width=»300″ height=»268″/></span></a></br> <a href=»javascript:void(0)»><img align=»left» style=»width:18px; height:18px; margin-right: 10px; margin-top: 2px;» src=»https://htmlforum.dev/topic/58626-pomogite-sdelat-body-na-ves-ekran/wp-content/themes/magnetto/layout/images/bg_level2_marker.png» alt=»»/><p><b>Внимание к деталям</b></p><span><img align=»left» style=»margin-bottom: 99px;» src=»http://www.mqsart.ru/wp-content/uploads/2017/01/workroom_full.png» alt=»» width=»300″ height=»268″/></span></a></br> <a href=»javascript:void(0)»><img align=»left» style=»width:18px; height:18px; margin-right: 10px; margin-top: 2px;» src=»https://htmlforum.dev/topic/58626-pomogite-sdelat-body-na-ves-ekran/wp-content/themes/magnetto/layout/images/bg_level2_marker.png» alt=»»/><p><b>Быстрая обучаемость</b></p><span><img align=»left» style=»margin-bottom: 99px;» src=»http://www.mqsart.ru/wp-content/uploads/2017/01/workroom_educability.png» alt=»» width=»300″ height=»268″/></span></a></br>
Нужна помощь с горизонтальным меню для сайта.
Мне нужно чтобы в меню все кнопки были сверху вместе с логотипом и в нем не оставалось пустого места, и что-бы было у всех одинаковое и не съезжало вниз от того что у человека маленький монитор.
Помогите решить данную проблему вот ссылка на меню: http://jsfiddle.net/u0tafr7v/ буду очень благодарен если поможете
Вот на фото пример как нужно что-бы было на сайте при любых расширениях экрана у пользователя.
А это что происходит при уменьшение браузера или с маленького монитора:
Make body have 100% of the browser height
I want to make body have 100% of the browser height. Can I do that using CSS?
I tried setting height: 100% , but it doesn’t work.
I want to set a background color for a page to fill the entire browser window, but if the page has little content I get a ugly white bar at the bottom.
25 Answers 25
Try setting the height of the html element to 100% as well.
Body looks to its parent (HTML) for how to scale the dynamic property, so the HTML element needs to have its height set as well.
However the content of body will probably need to change dynamically. Setting min-height to 100% will accomplish this goal.
![]()
As an alternative to setting both the html and body element’s heights to 100% , you could also use viewport-percentage lengths.
5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
In this instance, you could use the value 100vh — which is the height of the viewport.
This is supported in most modern browsers — support can be found here.
![]()
If you have a background image then you will want to set this instead:
This ensures that your body tag is allowed to continue growing when the content is taller than the viewport and that the background image continues to repeat/scroll/whatever when you start scrolling down.
Remember if you have to support IE6 you will need to find a way to wedge in height:100% for body, IE6 treats height like min-height anyway.
If you want to keep the margins on the body and don’t want scroll bars, use the following css:
Setting body
After testing various scenarios, I believe this is the best solution:
It is dynamic in that the html and the body elements will expand automatically if their contents overflow. I tested this in the latest version of Firefox, Chrome, and IE 11.
See the full fiddle here (for you table haters out there, you can always change it to use a div):
With that being said, there are several issues with the answers posted here.
Using the above CSS will cause the html and the body element to NOT automatically expand if their contents overflow as shown here:
As you scroll, notice the repeating background? This is happening because the body element’s height has NOT increased due to its child table overflowing. Why doesn’t it expand like any other block element? I’m not sure. I think browsers handle this incorrectly.
Setting a min-height of 100% on the body as shown above causes other problems. If you do this, you cannot specify that a child div or table take up a percentage height as shown here:
Hope this helps someone. I think browsers are handling this incorrectly. I would expect the body’s height to automatically adjust growing larger if its children overflow. However, that doesn’t seem to happen when you use 100% height and 100% width.
A better solution with modern CSS
![]()
What I use on the start of literally every CSS file I use is the following:
The margin of 0 ensures that the HTML and BODY elements aren’t being auto-positioned by the browser to have some space to the left or right of them.
The padding of 0 ensures that the HTML and BODY elements aren’t automatically pushing everything inside them down or right because of browser defaults.
The width and height variants are set to 100% to ensure that the browser doesn’t resize them in anticipation of actually having an auto-set margin or padding, with min and max set just in case some weird, unexplainable stuff happens, though you probably dont need them.
This solution also means that, like I did when I first started on HTML and CSS several years ago, you won’t have to give your first <div> a margin:-8px; to make it fit in the corner of the browser window.
Before I posted, I looked at my other fullscreen CSS project and found that all I used there was just body
Hope this detailed answer helps, and I feel your pain. In my eyes, it is dumb that browsers should set an invisible boundary on the left and sometimes top side of the body/html elements.
![]()
You can also use JS if needed
![]()
CSS Height That Works in Both Modern and Legacy Browsers
Most of the other solutions posted here will not work well in legacy browsers! And some of the code people posted will cause a nasty overflow of text beyond 100% height in modern browsers where text flows past background colors, which is bad design! So please try my code solution instead.
The CSS code below should support flexible web page height settings correctly in all known browsers, past and present:
NOTES ON THE CODE ABOVE
In many older, as well as newer browsers, if you do not set 100% height on the <html> selector, body will never achieve 100% height! So that is critical here.
The new viewport units ("vh") are redundant on the body selector and not necessary as long as you have set html selector to a height of either 100% or 100vh . The reason is the body always derives its values from the html parent. The exception is a few very old browsers from the past, so its best to set some height value for the body.
Some modern browsers using the body selector will not know how to inherit the viewport height directly. So again, always set your html selector to 100% height! You can still use "vh" units in body to bypass the parent html value and get its property dimensions directly from the viewport in most modern browsers, however. But again, its optional if the parent or root html selector has 100% height, which body will always inherit correctly.
Notice I’ve set body to height:auto , not height:100% . This collapses the body element around content initially so it can grow as content grows. You do NOT want to set body height and width to 100% , or specific values as that limits content to the body’s current visual dimensions, not its scrollable dimensions. Anytime you assign body height:100% , as soon as content text moves beyond the browser’s height, it will overflow the container and thus any backgrounds assigned to the original viewport height, creating an ugly visual! height:auto is your best friend in CSS!
But you still want body to default to 100% height, right? That is where min-height:100% works wonders! It will not only allow your body element to default to 100% height, but this works in even the oldest browsers! But best of all, it allows your background to fill 100% and yet stretch farther down as content with height:auto grows vertically.
Using overflow:auto properties are not needed if you set height:auto on the body . That tells the page to let content expand height to any dimension necessary, even beyond the viewport’s height, if it needs to and content grows longer than the viewport page display. It will not break out of the body dimensions. And it does allow scrolling as needed. overflow-y:scroll allows you to add an empty scrollbar to the right of the page content by default in every web browser. The scrollbar only appear inside the scroll bar area if content extends beyond 100% height of the viewport. This allows your page width, and any margins or paddings to be calculated by the browser beforehand and stop the pages from shifting as users view pages that scroll and those that do not. I use this trick often as it sets the page width perfectly for all scenarios and your web pages will never shift and load lightning fast!
I believe height:auto is the default on body in most UA browser style sheets. So understand most browsers default to that value, anyway.
Adding min-height:100% gives you the default height you want body to have and then allows the page dimensions to fill the viewport without content breaking out of the body. This works only because html has derived its 100% height based on the viewport.
The two CRITICAL pieces here are not the units, like % or vh , but making sure the root element, or html , is set to 100% of the viewport height. Second, its important that body have a min-height:100% or min-height:100vh so it starts out filling the viewport height, whatever that may be. Nothing else beyond that is needed.
STYLING HEIGHT FOR LEGACY BROWSERS
Notice I have added "fallback" properties for height and min-height , as many browsers pre-2010 do not support "vh" viewport units. It’s fun to pretend everyone in the web world uses the latest and greatest but the reality is many legacy browsers are still around today in big corporate networks and many still use antiquated browsers that do not understand those new units. One of the things we forget is many very old browsers do not know how to fill the the viewport height correctly. Sadly, those legacy browsers simply had to have height:100% on both the html element and the body as by default they both collapsed height by default. If you did not do that, browser background colors and other weird visuals would flow up under content that did not fill the viewport. The example above should solve all that for you and still work in newer browsers.
Before modern HTML5 browsers (post-2010) we solved that by simply setting height:100% on both the html and body selectors, or just min-height:100% on the body . So either solution allows the code above to work in over 20+ years of legacy web browsers rather than a few created the past couple of years. In old Netscape 4 series or IE 4-5, using min-height:100% instead of height:100% on the body selector could still cause height to collapse in those very old browsers and cause text to overflow background colors. But that would be the one issue I could see with this solution.
Using my CSS solution, you now allow your website to be viewed correctly in 99.99% of browsers, past and present rather than just 60%-80% of browsers built the past few years.
Как растянуть body и html на всю высоту браузера?
Есть такой глюк на странице, html и body не растягиваются на всю высоту браузера из-за этого все внутренние элементы выходят за ее пределы. Как это исправить?
Вместе с содержимым container тоже на всю высоту:
А вот если Вы об этом, что вн. контент больше высоты экрана (высоты body, html ):
Тогда либо убрать для body, html высоту в 100%, либо задавать минимальную высоту ( min-height: 100vh или min-height: 600px ).

Вот код без min-height: 100vh :
А вот код с ним:

Не фиксируй высоту явно, всегда min-height задавай. А то если дочерние компоненты превысят высоту, начнут выпадать из контейнера.

можно и так сделать, а содержимое уже высоту определит. Залей на гитхаб может, и ссылку дай

Не совсем понимаю проблему. Для html не видел чтобы css задавали, он и без них нормально тянется. Для body зафиксировал высоту, и контейнеры выпадать стали.
У первого контейнера высота минимальная задана, поэтому он увеличивает высоту, так как второй контейнер превысил эту высоту.