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

How to fix CSS height 100 not working

Fix issues with setting height 100%. This post goes over four steps to identify and fix setting height 100.

Dec 9, 2022 | Read time 8 minutes

🔔 Table of contents

One frustrating thing when design web pages is the height 100% not working correctly. For example, the content overflows from the parent!

The main reason why using CSS height:100 property is not working for your design is mainly due to how the parent is structured.

This post will go over a few steps or checklist on how to approach this issue.

Читайте также:  Сверточная нейронная сеть python код

Steps to take to fix height 100% not working issues

  1. Check that the HTML and CSS is valid — no typos, and use on non-replaced inline elements
  2. Check the parent element height. The additionally, check if there is content in the element.
  3. Are you using min-height or max-height? These properties override the values of height .
  4. Remove height settings if using flex layouts.

Check that the HTML and CSS is valid!

CSS height property can be applied to all elements and controls the height of the content area.

The first thing to check when it is not working is to check the syntax. Check that you are not having any typos, or using invalid values, etc:

When using percentages (%), also make sure that you are specifying the number correctly. The following will not be valid numbers to use for percentages:

Tip: Height will not work with non-replaced inline elements.

Check the parent element height

When we set an element to be height:100% , we need to consider the parent element. According to the specifications, when using percentages, the height is calculated as the percentage of the containing block’s height.

In most cases, we need to explicitly specify the height of the parent element ( body and html tag) to height:100% .

Take the following example when specifying height 100% on the .main class is not working:

 See the Pen Untitled by ⭐ Kentaro ⭐ (@kentaro_au) on CodePen.

To fix this, we specify a height for the and tags:

Tip: Make sure to specify the height of both body and html tags

Are you using min-height or max-height?

An example of when height 100% will not work is when you have not properly used the min-height or max-height . Lets consider the following code that will not work:

  Similar to the previous example, since the and tags do not specify the height value, the height:100% on the .main class will not take effect.

The min-height CSS property just sets the minimum height of the element. To fix this, we just change the min-height to height on the html and body tags.

Remove height settings if using flex layouts

A common misunderstanding with height 100% issues is when we are combining it with flex layouts.

See the Pen Untitled by ⭐ Kentaro ⭐ (@kentaro_au) on CodePen.

 From the example, we cannot see .flex-1 is not appearing at all. We can see that the width for .flex-1 is being applied but not the height 100% setting.
 To fix this, we just need to remove the height:100% and we can see that the .flex-1 with background of acqua is now appearing.

Why does this work? When using flex the align-items control the vertical behavior.

This has the default value of stretch so it just works naturally.

When we introduce height:100% , this overrides the flex calculation.

The calculation of the height of .flex-1 now depends on the parent element ( .container ).

Since the parent does not have a explicit height -> the child element’s height becomes zero.

Tip: Use vh instead of height 100% percentage

vh is the height of the viewport. This will give you a element that covers the height of the viewable area of the screen and would have the intended effect of filling the whole page.

Additionally, depending on the device and orientation, you may want to use vm (eg landscape)

Browser suppport

  • height is widely supported with modern browsers and older versions. This is because this value has been fundamental and exists ever since the CSS1 specifications
  • some issues with IE10 and IE11 do not appear to support overriding min-width or max-width values using the initial value.
  • max-width doesn’t work with images in table cells in IE.

Summary

In this post we looked at a common issue with web design of setting height 100. The most common reason is that the parent element is not explicitly setting the height.

Changing the AND tags to have height:100% will mostly fix the majority of styling issues. Other issues arise when we use flex layouts. It is recommended not to mix height:100% with flex layouts since flex items come initially with align-items:stretch .

Additionally misuse of the min-height and max-height properties can cause issues. These properties can override the height values.

👋 About the Author

G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

👉 See Also 👈

Источник

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 тег

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

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

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

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

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

Атрибуты

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

Пример

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

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

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

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