Как растянуть body на весь экран html

от admin

HTML vs Body: How to Set Width and Height for Full Page Size

Dave Gray

Dave Gray

HTML vs Body: How to Set Width and Height for Full Page Size

CSS is difficult but also forgiving. And this forgiveness allows us to haphazardly throw styles into our CSS.

Our page still loads. There is no «crash».

When it comes to page width and height, do you know what to set on the HTML element? How about the body element?

Do you just slap the styles into both elements and hope for the best?

If you do, you’re not alone.

The answers to those questions are not intuitive.

I’m 100% guilty of applying styles to both elements in the past without considering exactly which property should be applied to which element. ��‍♂️

It is not uncommon to see CSS properties applied to both the HTML and body elements like this:

Does It Matter?

Yes, yes it does.

The above style definition creates a problem:

Setting min-height to 100% on both elements does not allow the body element to fill the page like you might expect. If you check the computed style values in dev tools, the body element has a height of zero.

Meanwhile, the HTML element has a height equal to the visible part of the page in the browser.

Look at the following screenshot from Chrome Dev Tools:

empty_body

The body element has a default 8px margin indicated by the bar on top. The height value is 0.

Why Does This Happen?

Using a percentage as a size value requires the element to reference a parent to base that percentage on.

The HTML element references the viewport which has a height value equal to the visible viewport height. However, we only set a min-height on the HTML element. NOT a height property value.

Therefore, the body element has no parent height value to reference when deciding what 100% is equal to.

And The Problem May Be Hidden

If you started out with enough content to fill the body of the page, you might not have noticed this issue.

And to make it more difficult to notice, if you set a background-color on both elements or even on just one of them, the viewport is full of that color. This gives the impression the body element is as tall as the viewport.

It’s not. It’s still at zero.

The image above is taken from a page with the following CSS:

Reverse-inheritance?

In a strange twist, the HTML element assumes the background-color of the body element if you don’t set a separate background-color on the html element.

So What is the Ideal Height Setting for a Full Responsive Page?

For years, the answer was the following:

This allows the HTML element to reference the parent viewport and have a height value equal to 100% of the viewport value.

With the HTML element receiving a height value, the min-height value assigned to the body element gives it an initial height that matches the HTML element.

This also allows the body to to grow taller if the content outgrows the visible page.

The only drawback is the HTML element does not grow beyond the height of the visible viewport. However, allowing the body element to outgrow the HTML element has been considered acceptable.

The Modern Solution is Simplified

This example uses vh (viewport height) units to allow the body to set a minimum height value based upon the full height of the viewport.

Like the previously discussed background-color, if we do not set a height value for the HTML element, it will assume the same value for height that is given to the body element.

Therefore, this solution avoids the HTML element overflow present in the previous solution and both elements grow with your content!

The use of vh units did cause some mobile browser issues in the past, but it appears that Chrome and Safari are consistent with viewport units now.

Page Height May Cause a Horizontal Scrollbar

Shouldn’t this say «Page Width»?

In another strange series of events, your page height may activate the horizontal scrollbar in your browser.

When your page content grows taller than the viewport height, the vertical scrollbar on the right is activated. This can cause your page to instantly have a horizontal scrollbar as well.

So What is the Fix?

You may sleep better knowing it starts with a page width setting.

This problem arises when any element — not just the HTML or body element — is set to 100vw (viewport width) units.

The viewport units do not account for the approximate 10 pixels that the vertical scrollbar takes up.

Therefore, when the vertical scrollbar activates you also get a horizontal scrollbar.

Читать:
Как получить данные авторизированного пользователя laravel

How to Set the Page for Full Width

Maybe just don’t.

Not setting a width on the HTML and body elements will default to the full size of the screen. If you do set a width value other than auto, consider utilizing a CSS reset first.

Remember, by default the body element has 8px of margin on all sides.

A CSS reset removes this. Otherwise, setting the width to 100% before removing the margins will cause the body element to overflow. Here’s the CSS reset I use:

How to Set Width to Your Preference

While it may not always be necessary to set a width, I usually do.

It may simply be a habit.

If you set the width to 100% on the body element you will have a full page width. This is essentially equivalent to not setting a width value and allowing the default.

If you want to use the body element as a smaller container and let the HTML element fill the page, you could set a max-width value on the body.

Here’s an example:

Conclusion

With no height value provided for the HTML element, setting the height and/or min-height of the body element to 100% results in no height (before you add content).

However, with no width value provided for the HTML element, setting the width of the body element to 100% results in full page width.

This can be counterintuitive and confusing.

For a responsive full page height, set the body element min-height to 100vh.

If you set a page width, choose 100% over 100vw to avoid surprise horizontal scrollbars.

I’ll leave you with a tutorial from my YouTube channel demonstrating the CSS height and width settings for an HTML page that is full screen size and grows with the content it contains:

Do you have a different way of setting the CSS width and height that you prefer?

Как правильно задать 100% высоту body и html при верстке, чтобы потом не было проблем?

Lynn

Что делает этот код? Для чего все эти свойства?
Для чего вы и так блочным элементам даёте 100% ширину? Так как в данном коде width: 100% ну вообще не нужно!

По делу:
Учите наследование! % всегда берутся от родительского элемента. И если размер у родителя не указан, то и проценты не сработают!

У body родитель html, а у html окно браузера. Что бы растянуть body на 100%, нужно сначала html дать 100%, а потом body, а потом вашему #intro. Вот тогда #intro растянется на 100%.

Как растянуть body и html на всю высоту браузера?

Есть такой глюк на странице, html и body не растягиваются на всю высоту браузера из-за этого все внутренние элементы выходят за ее пределы. Как это исправить?

Вместе с содержимым container тоже на всю высоту:

А вот если Вы об этом, что вн. контент больше высоты экрана (высоты body, html ):

Тогда либо убрать для body, html высоту в 100%, либо задавать минимальную высоту ( min-height: 100vh или min-height: 600px ).

SVE's user avatar

Вот код без min-height: 100vh :

А вот код с ним:

Andrei Fedorov's user avatar

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

Denis's user avatar

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

Denis's user avatar

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

У первого контейнера высота минимальная задана, поэтому он увеличивает высоту, так как второй контейнер превысил эту высоту.

Как сделать блок на всю высоту страницы

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

И по такому случаю давайте реализуем блок на весь экран средствами CSS. Кстати, если хотите сделать по экранную прокрутку, то я делал обзор на JS-плагины экранной прокрутки (скроллинг). Вернемся к нашей задачи. Итак, вот один из примеров, как это можно сделать.

Берем DIV или можно section , и присваиваем ему высоту, использовав единицу измерения vh – это относительно 1% высоты окна просмотра. Пример:

Вот мы и получили нужный результат. Ну а дальше уже можно подгонять под себя. К примеру, сделать два блока с обтеканием.

Есть также и другие варианты реализации. Это может быть flex , JavaScript и другое. Но этот рабочий и кроссбраузерный. Ну, если, конечно, браузер не очень старый. В Internet Explorer 8 этот способ не работает, а начиная с 9 все отлично.

Related Posts