Заголовок документа

HTML тег

HTML тег определяет содержимое (контент) HTML-документа, которое отображается в окне браузера (текст, ссылки, картинки (изображения), таблицы, списки и т.д.). Он должен быть единственным в документе и всегда должен располагаться внутри элемента , сразу после элемента .

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

Примечание: все атрибуты (vlink, text, link, bgcolor, background, alink), ранее используемые с элементом , считаются устаревшими и запрещены к использованию в HTML5, поэтому для определения цвета заднего фона, цвета текста или ссылок, а так же для добавления фонового изображения и т.д. используйте CSS.

Элемент является блочным и по умолчанию имеет небольшой внешний отступ со всех сторон, его высота определяется его содержимым. Чтобы растянуть его на всю высоту окна браузера, нужно указать высоту для него и для элемента равную 100%:

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

Содержание
  1. Атрибуты
  2. Стиль по умолчанию
  3. Пример
  4. HTML vs Body: How to Set Width and Height for Full Page Size
  5. Does It Matter?
  6. Why Does This Happen?
  7. And The Problem May Be Hidden
  8. Reverse-inheritance?
  9. So What is the Ideal Height Setting for a Full Responsive Page?
  10. The Modern Solution is Simplified
  11. Page Height May Cause a Horizontal Scrollbar
  12. So What is the Fix?
  13. How to Set the Page for Full Width
  14. How to Set Width to Your Preference
  15. Conclusion
  16. Make Take Up 100% of the Browser Height
  17. How Percentage Sizes are Calculated
  18. Conclusion
  19. The KIRUPA Newsletter
Читайте также:  Posting images in php

Атрибуты

Стиль по умолчанию

Пример

     Содержимое страницы  

Результат данного примера в окне браузера:

Пример использования тега <body data-lazy-src=

Копирование материалов с данного сайта возможно только с разрешения администрации сайта
и при указании прямой активной ссылки на источник.
2011 – 2023 © puzzleweb.ru

Источник

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?

Источник

Make Take Up 100% of the Browser Height

Look, it

Look, it

Ok, so here is the setup! A short while ago, I was trying to listen for mouse events on the body of a mostly empty page. What I wanted to do was make the body element take up the full height of the page so that I have a giant hit target that I can do all sorts of event-related shenanigans on. Knowing what I had to do, I specified the body element in the HTML and wrote some CSS that looked as follows:

When I previewed this page in the browser, this is what I saw:

a big yellow background

From what you and I can see, the body element seems to take up the full size of the page. The yellow background color we specified in the CSS fills up everything. Life seems good. Right? Despite what you see, this is one of the many cases involving HTML and CSS where looks can be deceiving. Your body element literally has a height of 0. Let’s pause for a moment and let that sink in. Take a measured walk around the room if needed.

Once you are ready, read on to learn both why you have such a bizarre height and how to fix it so that our body element truly takes up 100% of the available space.

How Percentage Sizes are Calculated

In HTML and CSS, some of the greatest mysteries revolve around two things:

To follow along and help explain the confusion around this topic, take a look at the following markup:

This is the full markup for the example you saw earlier, and if you preview all of this in your browser, you’ll see an empty page with a yellow background. Our goal is to have our body element take up the full height of the page, and despite overwhelming evidence to the contrary, that isn’t happening right now. You can verify that this isn’t happening when you inspect the height of the body element using an in-browser development tool such as what you get with Chrome:

small screenshot

Notice that the reported height of the body element in the box model visualization is in fact 0 pixels. This means that your body element might as well not exist from a visual point of view. What is going on here?

To fully understand what is going on here, let’s learn a bit about how the html and body elements are sized along with some general height calculation trivia. By default, both the html element and body element have their height CSS property set to auto. This means they don’t have an explicit height out of the box. They’ll either take up whatever height they are told to be, or they will take up whatever height of the content that is inside them.

Doesn’t the highlighted line satisfy the «they’ll take up whatever height they are told to be» part of what I wrote earlier? The answer is “No” and the reason has to do with what a percentage value for height actually means. Allow me to bore you with the relevant information from the spec:

The percentage is calculated with respect to the height of the generated box’s containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to ‘auto’. A percentage height on the root element is relative to the initial containing block.

The emphasized part holds the key. See, our body element’s height is set to be 100% of the height of the containing block. The containing block is the html element, and we never specified a height on it. Because there isn’t any content on the page, the height of the html element. wait for it. is also 0. The solution to our problem then would be to specify a height value of 100% on the html element as well:

Once you do this, the height of our body element naturally becomes the 100% height that we had always wanted it to be:

body has a size now

There is just one more thing we need to do. Your body element will often contain more content than can be displayed in one screen of your browser. In such cases, you will want a scrollbar to appear and not have your body element’s size fixed to whatever initial size your browser was. There is an easy fix to address this valid concern — replace the height property on the body element with min-height instead:

This will ensure your body element’s size grows along with the content inside it. If you have no content in your body element, the body will take up all the space available to it anyway.

Conclusion

The twisted path to writing this article started with something completely unrelated — making the body element a click/hit area as big as the browser window. Figuring all of this out was 80% fun and 20% frustrating, but the result is that I learned a lot about how sizing in HTML/CSS works. I hope my rambling writing here helped you to learn more about it as well.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa

new books - yay.

  • Arrays From Noob to Ninja
    • BUY
  • JavaScript Absolute Beginner’s Guide
    • BUY
  • Learning React:
    A Hands-on Guide
    • BUY
  • Creating Web Animations
    • BUY

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 — delivered weekly to over a bazillion subscribers!

Serving you freshly baked content since 1998!
Killer hosting by GoDaddy

Источник

Оцените статью