Высота всего документа html

Ширина (width) и высота (height) в HTML

В этой статье рассмотрим, как можно задавать ширину и какими свойствами стоит делать это. Для первого примера возьмём блочный элемент div. По умолчанию он имеет высоту равную нулю (если ничего не содержит) и занимает 100% ширины родительского элемента. Попробуем задать ему ширину в 200 пикселей и высоту в 150. Для этого используем CSS свойства width (ширина) и height (высота):

Можно задавать ширину не только в пикселях, но и в процентах от ширины родительского элемента. Попробуем сделать это:

К сожалению, задать высоту для блочного элемента в процентах не получится. Если написать «height:50%;», то в разных браузерах будет диаметрально противоположный результат, поэтому лучше считать такую запись ошибкой.

Только у одного элемента можно задать свойство height в процентах, а точнее у псевдоэлементов :before и ::after. Читайте о них в статье Псевдоэлементы (:before, ::after)

Максимальная и минимальная ширина (max-width и min-width)

Жёсткое ограничение ширины — это не лучший способ строить сайт. Потому что в таком случае появятся проблемы с адаптацией под мобильные и планшеты: ширина экрана может быть меньше ширины блока. Тогда часть сайта будет выходить пределы вёрстки сайта и появится горизонтальная прокрутка, чего у версии сайта на мобильном быть не должно. Поэтому вместо жёсткого задания ширины используется ограничение сверху через CSS свойство max-width. Мы знаем, что блочный элемент div пытается занять всю ширину родительского элемента, как будто по умолчанию у него есть свойство width и оно имеет значение 100%.

Но теперь, если вы возьмёте окно своего браузера и сузите до 400 пикселей и меньше, то увидите как контейнер div уменьшает свои размеры, чтобы не выпрыгивать за пределы вёрстки. Если же изменить «max-width:400px;» на «width:400px», то блок будет выходить за пределы родительского элемента:

Читайте также:  Javascript закрыть другое окно

По смыслу свойство min-width является диаметрально противоположным к max-width. Оно ограничивает минимальную ширину элемента, но не ограничивает максимальную.

Максимальная и минимальная высота (max-height и min-height)

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

Рассмотрим наглядный пример необходимости использования max-height. Допустим, что нам надо сделать чат, где пользователи сайта смогут обмениваться текстовыми сообщениями. Для этого нужно создать контейнер, который будет расти по мере появления в нём новых сообщений. Но как только div достигает определённой высоты, то перестаёт расти и появится полоса прокрутки. Используем следующий CSS код:

 
Тише, мыши, кот на крыше, а котята ещё выше. Кот пошёл за молоком, а котята кувырком. Кот пришёл без молока, а котята ха-ха-ха.

Весь текст не вместится в div. Поэтому из-за свойства «overflow-y: scroll;» появится полоса прокрутки:

Тише, мыши, кот на крыше, а котята ещё выше. Кот пошёл за молоком, а котята кувырком. Кот пришёл без молока, а котята ха-ха-ха.

Благодаря атрибуту contenteditable=»true» у тега div в примере, Вы можете изменить текст внутри контейнера. Попробуйте удалить и добавить несколько строк. Размер контейнера будет подстраиваться под количества текста в нём до тех пор, пока не станет быть равен 100px. Затем появится полоса прокрутки.

По смыслу свойство min-height является диаметрально противоположным к max-height. Оно ограничивает минимальную высоту элемента, но не ограничивает максимальную.

Источник

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.

div  height: 100%; width: 100%; font-size: 20px; background-color: lightskyblue; > 

./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 ?

div  /* height: 100% */ height: 865px; /* current height of my browser */ /* . */ > 

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%

html, body  height: 100%; width: 100%; > div  height: 100%; /* . */ > 

Works! (We’ll fix the scrollbars later) By setting both and its child 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. In this case:

  • 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.

html, body  /* height: 100%; */ /* width: 100% */ > div  /* height: 100%; width: 100%; */ height: 100vh; width: 100vw; /* . */ > 

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 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.

body  height: 100vh; width: 100vw; > div  height: 100%; width: 100%; /* height: 100vh; width: 100vw; */ /* . */ > 

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?

and 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 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:

html, body  margin: 0; padding: 0; > body . 

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.

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

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

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

Источник

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