Размеры в CSS3

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?

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

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

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.

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.

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?

Источник

Для чего указывать ширину и высоту для html body?

Можно ли тегу Body задавать ширину и высоту?
Решил перейти на html5, скачал книгу и автор задает тегу body ширину и меня это смутило. Правильно.

и на всю высоту страницы
Добрый день! пишу сайт http://usahotsale.esy.es/. Подскажите пожалуйста как растянуть <html> и.

Для чего указывать array()?
Добрый день! Ниже код верификации, взятый из книги Скляра. Если вводится неправильный пароль.

В чем логика установки разных размеров шрифтов для html и для body?
Почему в Bootstrap для тега html установлен font-size: 10px; а для тега body 14px? Не пойму в.

Эксперт HTML/CSS

Лучший ответ

Сообщение было отмечено Fedor92 как решение

Решение

phpk, это указывает на то что Ваш сайт будет отображаться на всю ширину и высоту окна браузера. Иногда когда сайты верстаются на определённое разрешение, к примеру 1000px — если задать данную ширину для body — тогда тело Вашего сайт относительно окна браузера будет иметь ширину 1000px.

ЦитатаСообщение от Fedor92 Посмотреть сообщение

Вот код, который якобы должен показывать блок test с шириной в 1000px на всё окно браузера.
Но за границей блока с классом test видно фоновый цвет body!
Почему тогда видно body подскажите пожалуйста?
Хочется полностью разобраться в этих мелочах

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 html> head> title>test/title> meta charset="utf-8"> style> html, body < width: 1000px; height: 1000px; margin: 0; padding: 0; background-color: aqua; >.test < background-color: darkorange; width: 1000px; height: 1000px; min-width: 200px; >/style> /head> body> div class="test">Hello/div> /body> /html>

Эксперт HTML/CSS

Добавлено через 3 минуты
Ну так Вы не только же body задаёте границу, но и тегу html — вот она и проявилась. html(по умолчанию 100% на 100%) — нельзя задать фикс. размеры, а вот body — можно и нужно это делать.

ЦитатаСообщение от Fedor92 Посмотреть сообщение

body { width: 1000px; height: 1000px; background-color: aqua; margin: 0; padding: 0; }

Источник

Css задать ширину body

Размеры элементов задаются с помощью свойств width (ширина) и height (высота).

Значение по умолчанию для этих свойств — auto , то есть браузер сам определяет ширину и высоту элемента. Можно также явно задать размеры с помощью единиц измерения (пикселей, em) или с помощью процентов:

width: 150px; width: 75%; height: 15em;

Пиксели определяют точные ширину и высоту. Единица измерения em зависит от высоты шрифта в элементе. Если размер шрифта элемента, к примеру, равен 16 пикселей, то 1 em для этого элемента будет равен 16 пикселям. То есть если у элемента установить ширину в 15em, то фактически она составит 15 * 16 = 230 пикселей. Если же у элемента не определен размер шрифта, то он будет взят из унаследованных параметров или значений по умолчанию.

Процентные значения для свойства width вычисляются на основании ширины элемента-контейнера. Если, к примеру, ширина элемента body на веб-странице составляет 1000 пикселей, а вложенный в него элемент имеет ширину 75%, то фактическая ширина этого блока составляет 1000 * 0.75 = 750 пикселей. Если пользователь изменит размер окна браузера, то ширина элемента body и соответственно ширина вложенного в него блока div тоже изменится.

Процентные значения для свойства height работают аналогично свойству width, только теперь высота вычисляется по высоте элемента-контейнера.

     div.outer < width: 75%; height: 200px; margin: 10px; border: 1px solid #ccc; background-color: #eee; >div.inner  

Ширина и высота в CSS 3

В то же время фактические размеры элемента могут в итоге отличаться от тех, которые установлены в свойствах width и height . Например:

     div.outer  
Определение фактического размера в CSS 3

Фактические размеры в CSS 3

Как видно на скриншоте, в реальности значение свойства width — 200px — определяет только ширину внутреннего содержимого элемента, а под блок самого элемента будет выделяться пространство, ширина которого равна ширине внутреннего содержимого (свойство width) + внутренние отступы (свойство padding) + ширина границы (свойство border-width) + внешние отступы (свойство margin). То есть элемент будет иметь ширину в 230 пикселей, а ширина блока элемента с учетом внешних отступов составит 250 пикселей.

Подобные расчеты следует учитывать при определении размеров элементов.

С помощью дополнительного набора свойств можно установить минимальные и максимальные размеры:

  • min-width : минимальная ширина
  • max-width : максимальная ширина
  • min-height : минимальная высота
  • max-height : максимальная высота
min-width: 200px; width:50%; max-width: 300px;

В данном случае ширина элемента равна 50% ширины элемента-контейнера, однако при этом не может быть меньше 200 пикселей и больше 300 пикселей.

Переопределение ширины блока

Свойство box-sizing позволяет переопределить установленные размеры элементов. Оно может принимать одно из следующих значений:

    content-box : значение свойства по умолчанию, при котором браузер для определения реальных ширины и высоты элементов добавляет берет соответственно значения свойств width и height элемента . Например:

width: 200px; height: 100px; margin: 10px; padding: 10px; border: 5px solid #ccc; background-color: #eee; box-sizing: content-box;

В данном случае элемент будет иметь ширину в 200 пикселей и высоту в 100 пиксей.

width: 200px; height: 100px; margin: 10px; padding: 10px; border: 5px solid #ccc; background-color: #eee; box-sizing: padding-box;
width: 200px; height: 100px; margin: 10px; padding: 10px; border: 5px solid #ccc; background-color: #eee; box-sizing: border-box;

Например, определим два блока, которые отличаются только значением свойства box-sizing:

     div < width: 200px; height: 100px; margin: 10px; padding: 10px; border: 5px solid #ccc; background-color: #eee; >div.outer1 < box-sizing: content-box; >div.outer2  
Определение фактического размера в CSS 3
Определение фактического размера в CSS 3

В первом случае при определении размеров блока к свойствам width и height будут добавляться толщина границы, а также внутренние и внешние отступы, поэтому первый блок будет иметь большие размеры:

Источник

width

Устанавливает ширину блочных или заменяемых элементов (к ним, например, относится тег ). Ширина не включает толщину границ вокруг элемента, значение отступов и полей.

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

Синтаксис

width: значение | проценты | auto | inherit

Значения

В качестве значений принимаются любые единицы длины, принятые в CSS — например, пикселы (px), дюймы (in), пункты (pt) и др. При использовании процентной записи ширина элемента вычисляется в зависимости от ширины родительского элемента. Если родитель явно не указан, то в его качестве выступает окно браузера.

auto Устанавливает ширину исходя из типа и содержимого элемента. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

Результат данного примера, как он отображается в браузере Safari показан на рис. 1.

Ширина блока

Объектная модель

[window.]document.getElementById(» elementID «).style.width

Браузеры

Браузер Internet Explorer 6 некорректно определяет width как min-width . В режиме совместимости (quirk mode) Internet Explorer до версии 8.0 включительно неправильно вычисляет ширину элемента, не добавляя к ней значение отступов, полей и границ.

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

Читайте также:  Пишем движок на php mvc
Оцените статью