Как растянуть body на весь экран html
Перейти к содержимому

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

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.

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?

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

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

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

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

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

user avatar

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

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

user avatar

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

user avatar

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

user avatar

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

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

Сделать тело на 100% высоты браузера

Я хочу, чтобы body имел 100% высоты браузера. Могу ли я сделать это с помощью CSS?

Я попытался установить height: 100% , но это не работает.

Я хочу установить цвет фона для страницы, чтобы заполнить все окно браузера, но если на странице мало контента, я получаю уродливую белую полосу внизу.

Попробуйте также установить высоту HTML-элемента на 100%.

Тело ищет своего родителя (HTML), как масштабировать динамическое свойство, поэтому для HTML-элемента также должна быть установлена ​​его высота.

Однако содержание тела, вероятно, нужно будет динамически менять. Установка минимальной высоты на 100% позволит достичь этой цели.

В качестве альтернативы настройки оба html и body элемента высот 100% , вы можете также использовать окно просмотра-процентную длину.

5.1.2. Длина в процентах от области просмотра: единицы измерения: ‘vw’, ‘vh’, ‘vmin’, ‘vmax’

Длина области просмотра в процентах относится к размеру исходного содержащего блока. Когда высота или ширина исходного содержащего блока изменяется, они масштабируются соответственно.

В этом случае вы можете использовать значение 100vh — высоту области просмотра.

Это поддерживается в большинстве современных браузеров — поддержку можно найти здесь .

Если у вас есть фоновое изображение, вы можете установить это вместо:

Это гарантирует, что ваш тег body будет продолжать расти, когда содержимое выше, чем область просмотра, и что фоновое изображение будет повторяться / прокручиваться / что угодно, когда вы начнете прокручиваться вниз.

Помните, что если вам нужно поддерживать IE6, вам нужно будет найти способ втиснуть height:100% тело, IE6 работает height как и в min-height любом случае.

Если вы хотите сохранить поля на теле и не хотите использовать полосы прокрутки, используйте следующую CSS:

Установка body даст вам полосы прокрутки.

После тестирования различных сценариев, я считаю, что это лучшее решение:

Это динамично в том, что html и body элементы будут расширяться автоматически , если их переполнения содержимого. Я проверил это в последней версии Firefox, Chrome и IE 11.

Смотрите полную скрипку здесь (для вас ненавидят за столом, вы всегда можете изменить его, чтобы использовать div):

При этом, есть несколько вопросов с ответами, размещенными здесь .

Использование вышеуказанного CSS приведет к автоматическому расширению html и элемента body, если их содержимое переполнится, как показано здесь:

Как прокручиваете, замечаете повторяющийся фон? Это происходит потому, что высота элемента body НЕ увеличилась из-за переполнения дочерней таблицы. Почему он не расширяется как любой другой элемент блока? Я не уверен. Я думаю, что браузеры обрабатывают это неправильно.

Установка минимальной высоты тела на 100%, как показано выше, вызывает другие проблемы. Если вы сделаете это, вы не сможете указать, что дочерний элемент div или таблица занимают процентную высоту, как показано здесь:

Надеюсь, это кому-нибудь поможет. Я думаю, что браузеры обрабатывают это неправильно. Я ожидал бы, что рост тела автоматически отрегулируется, увеличиваясь, если его дети переполняются. Однако этого не происходит, когда вы используете 100% высоты и 100% ширины.

В начале буквально каждого CSS-файла я использую следующее:

Поле 0 гарантирует, что элементы HTML и BODY не будут автоматически позиционироваться браузером, чтобы иметь место слева или справа от них.

Заполнение 0 гарантирует, что элементы HTML и BODY не будут автоматически толкать все внутри них вниз или вправо из-за настроек браузера по умолчанию.

Варианты ширины и высоты установлены на 100%, чтобы браузер не изменял их размер в ожидании фактического наличия автоматически устанавливаемого поля или отступа, с минимальными и максимальными значениями на случай, если произойдут какие-то странные, необъяснимые вещи, хотя вы вероятно, они не нужны.

Это решение также означает, что, как и я, когда я впервые начал работать с HTML и CSS несколько лет назад, вам не нужно будет указывать свой первый <div> вариант, margin:-8px; чтобы он поместился в углу окна браузера.

Перед публикацией я посмотрел свой другой полноэкранный CSS-проект и обнаружил, что все, что я использовал, было только body и ничего, что работало хорошо в течение двух лет, над которыми я работал.

Надеюсь, этот подробный ответ поможет, и я чувствую вашу боль. На мой взгляд, глупо, что браузеры должны устанавливать невидимую границу на левой, а иногда и на верхней стороне элементов body / html.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *