Hello World

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?

Источник

Как изменить ширину сайта?

Доброго.
Подскажите как указать максимальную ширину сайта. Изначально он был во весь экран (как тостер например), было принято решение применить блочный формат, но подскажите как уменьшить максимальную ширину сайта.
Если это важно: Bootstrap, двиг WP
Заранее спасибо!

Простой 2 комментария

SmthTo

5d6971e076e00492027937.jpeg
5d6971e5971ae869310989.jpeg

Это помимо того, что вопрос косой.

Ankhena

В бутстрапе есть 2 класса .container-fluid для 100% ширины и .container для фиксированной. Вероятно, вам нужно поменять container-fluid н container.
А может и нет. Мы же не знаем, что у вас в коде, может там все стили бутстрапа перебиты.

Чего не стоит делать, так это менять ширину тега body.

facepook

я не силен в html, но понимаю, что на мобилах тоже это будет работать и на узком экране (например айфон 5s минус 15% это будет не камильфо((

tuxfighter

Руслан Макаров, вы можете для разрешения iPhone 5s прописать хоть 1%, вбейте в поиске адаптивную верстку и как она делается, тогда поймете.

starhe

Раз человек задаёт подобный вопрос, значит ему бесполезно говорить «задайте max-width», он скорее всего просто не знает что это такое и где его задают.
Поэтому давайте так:
1. Откройте страницу вашего сайта.
2. Правой клавишей мыши откройте контекстное меню и выберите «Просмотр кода страницы» (это в Chrome в других браузерах может быть чуть по другому, но главное, чтоб были слова код и страница).
3. В отдельной вкладке откроется код вашей страницы, найдите в нём конструкцию (тег) /head. Делается это так: нажимаете комбинацию клавиш Ctrl+F и в правом верхнем углу появляется окно поиска. Вводите в него нужную конструкцию, в нашем случае /head, и этот тег сразу подсвечивается на странице с кодом.
4. Находите конструкцию (тег), который идёт сразу после тега /head. Это может быть wrapper, body, или что-то другое. В современных темах встречаются разные названия, видимо в целях безопасности или ещё чего. зависит от бзика разработчика, главное чтоб после тега /head
5. Идёте в админку вашего сайта и выбираете в меню слева «Внешний вид», а в нём «Редактор тем». Переходите.
6. Вам сразу откроется файл style.css. Именно он вам нужен.
7. Открываете Поиск (Ctrl+F) и вбиваете тот элемент, который вы нашли на странице с кодом после /head
8. Нюанс: в редакторе WordPress подсветятся только те элементы, которые находятся в видимой части экрана и если в вашей теме в начале файла style.css много комментариев, то поиск нужного элемента не увидит. Придётся найти его чисто визуально, что не будет особо сложно, так как такие элементы находятся обычно вверху файла. На сервере это было-бы делать проще, но учитывая вашу подготовку, я вас туда не посылаю.
9. Нужный вам элемент скорее всего будет в нескольких селекторах, в том числе и в групповых, где нескольким элементам заданы одни и те-же свойства, поэтому я рекомендую прописать в файле отдельный селектор, в любом месте после закрывающей скобки> такого вида

body (или другое название) max-width: 80%; (число на ваше усмотрение, можно задать в пикселях)
>

Сохраняем файл, смотрим что получилось и подгоняем нужную ширину.

Источник

Set size of HTML page and browser window

I have a div element with . I want to set this element to be the size of the viewable area in the browser window. I am using the following JS to do so.

var container= document.getElementById("container"); container.style.height=(window.innerHeight); container.style.width=window.innerWidth; 

However, the browser window size is larger than the viewable size and horizontal and vertical scroll bars appear. How do I make it so that my HTML page fits into the browser window without a need for scroll bars? EDIT: I am basically asking, how can I make the document size the same as the viewport size?

5 Answers 5

    html, body < width: 100%; height: 100%; margin: 0; padding: 0; background-color: green; >#container < width: inherit; height: inherit; margin: 0; padding: 0; background-color: pink; >h1  

Hello World

The background colors are there so you can see how this works. Copy this code to a file and open it in your browser. Try playing around with the CSS a bit and see what happens.

The width: inherit; height: inherit; pulls the width and height from the parent element. This should be the default and is not truly necessary.

Try removing the h1 < . >CSS block and see what happens. You might notice the layout reacts in an odd way. This is because the h1 element is influencing the layout of its container. You could prevent this by declaring overflow: hidden; on the container or the body.

I’d also suggest you do some reading on the CSS Box Model.

Источник

html/css to fit all screen resolution

I’m working on the website and I’m trying to make it responsive to all resolutions but without success..

body < width:1920px; background-color: #f8e0b3; height:1080px; >div.container < width:100%; height:100%; >div.header < background:url(img/header.jpg); width:100%; height:46%; margin-top:; margin-left:; border-bottom: 2px solid black; >h1.naslov < font-size:60px; color:white; margin:0 auto; margin-left:28%; font-family: Aramis; >p.naslov-text

  

Lorem ipsum nasov je?

"Lorem ipsum dolor sit amet, consectetur adipisicing elit."

When I resize my browser website doesn’t resize. I’ve been trying all morning and I’m really burnout. Do anyone know what logic to approach to make this fit all screens , but only using css.

Please provide a fiddle. And in the h1-element, the class has some whitespaces in it. I would delete them

You are setting a width and height of body in pixels. Thats strange both in general and for something that should be responsive.

But when I put body 100% 100% then it fits my screen 100%. And my screen is 1680 x 1050. I want to make it fits 1920 x 1080 and smaller.

I’ve managed to fix the width and that is working properly. But now height is problem. Height 100% is height of screen — but when I pass that height and scroll show height 100% become problem. Do anyone know how to fix height to work with resizing?

6 Answers 6

As you are giving a fixed width to your body and p.naslov-text, your website will not resize. Remove all px sizing and replace them with percentage values.

But if you want fixed sizes and also responsive you must use css media queries like that:

body < width:1920px; background-color: #f8e0b3; height:1080px; >@media screen and (min-width: 500px) < body < width:420px; >> @media screen and (min-width: 800px) < body < width:720px; >> 
#gallery-1 img < width:375px; >@media screen and (min-width: 1366px) < #gallery-1 img > @media screen and (min-width: 1440px) < #gallery-1 img > @media screen and (min-width: 1600px) < #gallery-1 img > @media screen and (min-width: 1920px) < #gallery-1 img > 

Reference: Stack Over Flow

Use jquery for resize window. This one is dynamic code for window resizing for all browsers.

Example code here using jquery:

$(document).ready(function()< $(window).resize(); >); $(window).resize(function< // your code var windowWidth=$(window).width(); var mainContainerWidth=windowWidth-100; // For example $("#yourMainContainer").css(); >); 

like that you will try for your main class width and height.

Источник

Читайте также:  Кнопка button в коде HTML формы
Оцените статью