Как сделать высоту блока на весь экран css

от admin

CSS Height Full Page CSS gotcha: How to fill page with a div?

So let’s say you want a div that fills up entire page.

Exit fullscreen mode

./Untitled.png

What?! It doesn’t work! The height still only takes up the content, but not the whole page.

The width is good since a div is by default a block element, which takes as much width as possible anyways.

Can we just use a more «absolute» value like px ?

Exit fullscreen mode

It works. until the browser is resized

It doesn’t adapt when the browser is resized.

You can use JS for this, but that’s way overkill for what we wanted.

I mentioned px is «absolute», but only in the sense that they are not relative to anything else (like rem and vh). But the actual size still depends on the device. Here’s some details:

Relative units to the rescue!

Old school height: 100%

Exit fullscreen mode

Works! (We’ll fix the scrollbars later)

By setting both <html> and its child <body> to 100% height, we achieve the full size.

Note that only setting either of them won’t work, since percentage is always relative to another value.

  • div is 100% the height of the body
  • body is 100% the height of the html
  • html is 100% the height of the Viewport

Viewport is the visible area of the browser, which varies by device.

For example, an iPhone 6/7/8 has a 375×667 viewport. You can verify this on your browser dev tools mobile options.

For now, you can think about viewport as the device pixel size or resolution. But if you want to go deep:

newer solution: viewport units vh and vw

Viewport-percentage lengths aka Viewport units have been around for a while now, and is perfect for responding to browser resizes.

  • 1 viewport height ( 1vh ) = 1% of viewport height
  • 1 viewport width ( 1vw ) = 1% of viewport width

In other words, 100vh = 100% of the viewport height

100vw = 100% of the viewport width

So these effectively fills up the device viewport.

Exit fullscreen mode

Looks good too! (We’ll fix the scrollbars later)

As mentioned in the comments by @angelsixuk and @mpuckett , there is a known jumping behavior during scrolling when using 100vh on mobile browsers, which is an issue but considered intentional by webkit. See these links for details: Viewport height is taller than the visible part of the document in some mobile browsers and Stack Overflow: CSS3 100vh not constant in mobile browser

How about min-height: 100vh ?

While height fixes the length at 100vh , min-height starts at 100vh but allows content to extend the div beyond that length. If content is less than the length specified, min-height has no effect.

In other words, min-height makes sure the element is at least that length, and overrides height if height is defined and smaller than min-height .

For our goal of having a div child with full height and width, it doesn’t make any difference since the content is also at full size.

A good use case of min-height is for having a sticky footer that gets pushed when there is more content on the page. Check this out here and other good uses of vh

A very common practice is to apply height: 100vh and width: 100vw to <body> directly.

In this case, we can even keep the container div relatively sized like in the beginning, in case we change our minds later.

And with this approach, we assure that our entire DOM body occupies full height and width regardless of our container div.

Exit fullscreen mode

vh/vw versus %

A good way of thinking about vh, vw vs % is that they are analogous to em and rem

% and em are both relative to the parent size, while vw/vh and rem are both relative to «the highest reference», root font size for rem and device viewport for vh/vw.

But why the scrollbar?

<html> and <body> have default margins and paddings!

Browsers feature a default margin, padding and borders to HTML elements. And the worst part is it’s different for each browser!

Chrome default for <body> has a margin: 8px

And 100vh + 8px causes an overflow, since it’s more than the viewport

Luckily, it’s fairly easy to fix that:

Exit fullscreen mode

This is a «blanket» solution that would cover all margin and padding variations for any browser you might have.

Cool! Now we have our div filling up the page without scrollbars!

no more scrollbars

Finally, let’s add a little padding, since it’s awkward that the content is right on the edges.

Exit fullscreen mode

What?! The scrollbar is back! What happened?

box-sizing border-box

box-sizing allows you to define whether the padding and border is included in the div’s height and width.

The default content-box of box-sizing doesn’t include padding and border in the length, so div becomes

  • height = 100% + 10px * 2
  • width = 100% + 10px * 2

which overflows the page!

border-box includes padding and border, so div stays at our required sizes:

  • height = 100%
  • width = 100%

It’s quite common to set all elements to border-box for a consistent layout and sizing throughout pages, using * selector:

Простой способ растянуть блок на всю высоту экрана, или CSS3 Viewport Units

В этой статье я познакомлю вас с появившимися в CSS3 единицами измерения vw, vh, vmin и vmax.

Что такое «Viewport Units»

Viewport Units — это относительные единицы измерения, рассчитывающиеся в процентах от размеров области просмотра браузера. Эти единицы измерения появились в третьей версии спецификации CSS .

Единицы измерения vh и vw

vh и vw можно расшифровать, как viewport height и viewport width — высота и ширина области просмотра соответственно. 1vh равен одному проценту от высоты области просмотра, 1vw равняется одному проценту от ширины области просмотра.

Единицы измерения vmin и vmax

vmin и vmax расшифровывается, как viewport minimal и viewport maximal. 1vmin сравнивает значения 1vh и 1vw , выбирая меньшее из них. 1vmax делает то же самое, но выбирает большее из двух значений. Иначе говоря, если у смартфона ширина экрана меньше высоты, то vmin будет рассчитываться относительно ширины, а vmax будет рассчитываться относительно высоты экрана.

Пример использования

Сейчас в тренде использование полноэкранных секций. Особенно часто их используют в лендингах. Есть много способов сделать такую секцию, однако самый простой и изящный способ — применить единицу измерения vh .

Как сделать div с height 100% с помощью CSS.

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

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

Читать:
Msvcp140d dll что это за ошибка как исправить

Но, как видите это свойство не работает. Блок не хочет растягиваться на всю ширину окна браузера.

Как решить эту проблему? Почему не работает свойство height:100%?

Все дело в том, что 100% должны браться от высоты родительского элемента. А какая у нас высота родительского элемента? Для элемента div, в данном примере, этими родительскими элементами являются элементы body и html.

По умолчанию, свойство height этих элементов принимает значение auto, а значит эти элементы имеют такую высоту, чтобы вместить в себе всю содержимое и не больше.

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

Давайте посмотрим, что из этого получиться.

Ну, вот, совсем другое дело. Теперь наш блок растянут на 100% высоты. Используйте это на практике.

How to make a div 100% height of the browser window

I have a layout with two columns — a left div and a right div .

The right div has a grey background-color , and I need it to expand vertically depending on the height of the user’s browser window. Right now, the background-color ends at the last piece of content in that div .

I’ve tried height:100% , min-height:100%; , etc.

Peter Mortensen's user avatar

40 Answers 40

There are a couple of CSS 3 measurement units called:

Viewport-Percentage (or Viewport-Relative) Lengths

What are Viewport-Percentage Lengths?

From the linked W3 Candidate Recommendation above:

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

These units are vh (viewport height), vw (viewport width), vmin (viewport minimum length) and vmax (viewport maximum length).

How can this be used to make a divider fill the height of the browser?

For this question, we can make use of vh : 1vh is equal to 1% of the viewport’s height. That is to say, 100vh is equal to the height of the browser window, regardless of where the element is situated in the DOM tree:

This is literally all that’s needed. Here is a JSFiddle example of this in use.

What browsers support these new units?

This is currently supported on all up-to-date major browsers apart from Opera Mini. Check out Can I use. for further support.

How can this be used with multiple columns?

In the case of the question at hand, featuring a left and a right divider, here is a JSFiddle example showing a two-column layout involving both vh and vw .

How is 100vh different from 100% ?

Take this layout for example:

The p tag here is set to 100% height, but because its containing div has 200 pixels height, 100% of 200 pixels becomes 200 pixels, not 100% of the body height. Using 100vh instead means that the p tag will be 100% height of the body regardless of the div height. Take a look at this accompanying JSFiddle to easily see the difference!

Peter Mortensen's user avatar

James Donnelly's user avatar

If you want to set the height of a <div> or any element, you should set the height of <body> and <html> to 100% too. Then you can set the height of element with 100% 🙂

Here is an example:

Josh Crozier's user avatar

If you’re able to absolutely position your elements,

Ry-'s user avatar

You can use the view-port unit in CSS:

HTML:

CSS:

Peter Mortensen's user avatar

DjaouadNM's user avatar

You can use vh in this case which is relative to 1% of the height of the viewport.

That means if you want to cover off the height, just simply use 100vh .

Look at the image below I draw for you here:

How to make a div 100% height of the browser window?

Try the snippet I created for you as below:

Alireza's user avatar

All the other solutions, including the top-voted one with vh are sub-optimal when compared to the flex model solution.

With the advent of the CSS flex model, solving the 100% height problem becomes very, very easy: use height: 100%; display: flex on the parent, and flex: 1 on the child elements. They’ll automatically take up all the available space in their container.

Note how simple the markup and the CSS are. No table hacks or anything.

The flex model is supported by all major browsers as well as IE11+.

Learn more about the flex model here.

You don’t mention a few important details like:

  • Is the layout fixed width?
  • Are either or both of the columns fixed width?

Here’s one possibility:

There are many variations on this depending on which columns need to be fixed and which are liquid. You can do this with absolute positioning too but I’ve generally found better results (particularly in terms of cross-browser) using floats instead.

Peter Mortensen's user avatar

This is what worked for me:

Use position:fixed instead of position:absolute , that way even if you scroll down the division will expand to the end of the screen.

Mobarak Ali's user avatar

Here’s a fix for the height.

In your CSS use:

For browser that don’t support vh-units , use modernizr.

Add this script (to add detection for vh-units )

Finally use this function to add the height of the viewport to #your-object if the browser doesn’t support vh-units :

Peter Mortensen's user avatar

Even with all of the answers here, I was surprised to find that none really solved the problem. If I used 100vh height / min-height , the layout broke when the content was longer than a page. If I instead used 100% height / min-height , the layout broke when the content was less than the page height.

The solution I found, which solved both cases, was to combine the top two answers:

Peter Mortensen's user avatar

100vw = 100% of the width of the viewport.

100vh = 100% of the height of the viewport.

If you want to set the div width or height 100% of browser-window-size you should use:

For width: 100vw

For height: 100vh

Or if you want to set it smaller size, use the CSS calc function. Example:

Peter Mortensen's user avatar

Try this — tested:

In later versions, you can use vh :

Peter Mortensen's user avatar

lukaszkups's user avatar

100% works differently for width and height.

When you specify width: 100% , it means "take up 100% of the available width from the parent element or width of the window."

When you specify height: 100% , it only means "take up 100% of available height from the parent element." This means if you don’t specify a height at a top level element, the height of all the children will be either 0 or height of the parent, and that is why you need to set the topmost element to have a min-height of window height.

I always specify the body to have a min-height of 100vh and it makes positioning and calculations easy,

Related Posts