JS Bin

height

CSS атрибут height позволят обозначать высоту элемента. По умолчанию, свойство определяет высоту внутренней области. Если box-sizing имеет значение border-box , то свойство будет определять высоту области рамки.

Интерактивный пример

Атрибуты min-height и max-height при добавлении меняют значение height .

Синтаксис

/* Значения-ключевые слова */ height: auto; /* значения */ height: 120px; height: 10em; /* значения */ height: 75%; /* Глобальные значения */ height: inherit; height: initial; height: unset; 

Значения

Высота — фиксированная величина.

Высота в процентах — размер относительно высоты родительского блока.

border-box Экспериментальная возможность

content-box Экспериментальная возможность

Браузер рассчитает и выберет высоту для указанного элемента.

fill Экспериментальная возможность

Использует fill-available размер строки или fill-available размер блока, в зависимости от способа разметки.

max-content Экспериментальная возможность

Внутренняя максимальная предпочтительная высота.

min-content Экспериментальная возможность

Внутренняя минимальная предпочтительная высота.

available Экспериментальная возможность

Высота содержащего блока минус вертикальные margin , border и padding .

fit-content Экспериментальная возможность

  • внутренняя минимальная высота
  • меньшая из внутренней предпочтительной высоты и доступной высоты

Формальный синтаксис

height =
auto | (en-US)
(en-US) | (en-US)
min-content | (en-US)
max-content | (en-US)
fit-content( (en-US) )

=
| (en-US)

Пример

HTML

div id="taller">Я 50 пикселей в высоту.div> div id="shorter">Я 25 пикселей в высоту.div> div id="parent"> div id="child"> Моя высота - половина от высоты родителя. div> div> 

CSS

div  width: 250px; margin-bottom: 5px; border: 2px solid blue; > #taller  height: 50px; > #shorter  height: 25px; > #parent  height: 100px; > #child  height: 50%; width: 75%; > 

Результат

Проблемы доступности

Убедитесь, что элементы с height не обрезаются и / или не затеняют другое содержимое, когда страница масштабируется для увеличения размера текста.

Спецификации

Начальное значение auto
Применяется к все элементы, кроме незаменяемых строчных элементов, табличных колонок и групп колонок
Наследуется нет
Проценты Процент для генерируемого блока рассчитывается по отношению к высоте содержащего блока. Если высота содержащего блока не задана явно (т.е. зависит от высоты содержимого), и этот этот элемент позиционирован не абсолютно, значение будет auto . Процентная высота на корневом элементе относительна первоначальному блоку.
Обработка значения процент, auto или абсолютная длина
Animation type длина, проценты или calc();

Поддержка браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 15 июл. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

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

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

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

   

Блок, который должен растянуться на 100% высоты окна браузера

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

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

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

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

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

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

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

Больше моих уроков по HTML, CSS и верстке сайтов здесь.

Чтобы оставить сообщение, зарегистрируйтесь/войдите на сайт через:

Источник

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:

Источник

Как задать высоту блоку равной высоте видимой части экрана в браузере? Почему если написать body ничего не происходит?

Всем привет, возник трудность с верстанием:
login.png
Что конкретно?
57e394f076064d619ab00444580fcf87.png
Не могу задать высоту контейнеру в 80% от оставшейся высоты видимой части экрана браузера:

* < margin: 0; padding: 0; >body < background: #42668C; color: white; font-family: Arial, sans-serif; >a < color: white; text-decoration: none; >input[type=button] < background: #42668C; color: white; border: none; cursor: pointer; >.container < height: . /*600*/ >

Если высота моего дисплея 768px, то видимая часть с вычетом траты на меню пуск и вкладки — всего ~600px

       
Добро подаловать!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae rem optio, ut, dignissimos voluptatibus minus dicta quam tempore temporibus. Ex ullam, sapiente esse quibusdam sequi ad provident ipsa repudiandae quas.
Забыли пароль?

Чего я хочу избежать? Мне не нужна вертикально появляющейся прокрутка!
Почему она появляется или должна появится? Когда я дописываю свойство background liner-gradient(на макете явно он есть), то вот что у меня получается, тырк

Как быть? Почему если написать body ничего не происходит? Я ожидаю увидеть что height станет высотой оставшейся видимой части экрана браузера

CSS3 — для новых(IE8+) браузеров
Для современных браузеров подойдёт решение с CSS3 единицами ‘vh’. Для старых браузеров придётся использовать CSS2 или задействовать javascript

В любом случаи необходимо смотреть поддержку

CSS2 — для всех старых браузеров
Корневой элемент html на самом деле не самый верхней уровень на странице — им является «viewport». Для простоты, будем считать, что это окно браузера. Так вот, если установить height: 100% элементу html, то это то же самое, что сказать — стань такой же высоты, как окно браузера

Если не задать html , то body не имеет смысла

JavaScript(Jquery) — для старых браузеров и в самом крайнем случаи

function setHeiHeight() < $('#hei').css(< height: $(window).height() + 'px' >); > setHeiHeight(); // устанавливаем высоту окна при первой загрузке страницы $(window).resize( setHeiHeight ); // обновляем при изменении размеров окна

Источник

Читайте также:  Html webkit transform scale
Оцените статью