What's the best way to make an element of 100% minimum height across a wide range of browsers ?
В частности, если у вас есть макет с header и footer с фиксированным height,
как сделать так, чтобы средняя часть содержимого заполнила 100% пространство между ними, а footer прикреплен к нижней части?
В качестве пояснения, vh означает viewport height, поэтому вы также можете использовать vw для viewport width и vmin для самого маленького размера, viewport minimum.
Это решение даст нежелательные результаты в Chrome для Android (необходимо будет проверить в других мобильных браузерах, таких как Safari), потому что 100vh не будет таким же, как 100%. Фактически, высота 100% соответствует высоте экрана за вычетом адресной строки в верхней части экрана, а 100vh соответствует высоте экрана без адресной строки. Таким образом, использование 100vh не будет работать на Chrome для Android. Ваш нижний колонтитул будет ниже сгиба на высоту, соответствующую высоте адресной строки браузера.
Вы можете добиться этого с помощью Flexbox. См. Пример.
теперь день 100vh работает как шарм






Я использую следующий: Макет CSS - высота 100%
Min-height
The #container element of this page has a min-height of 100%. That way, if the content requires more height than the viewport provides, the height of #content forces #container to become longer as well. Possible columns in #content can then be visualised with a background image on #container; divs are not table cells, and you don't need (or want) the physical elements to create such a visual effect. If you're not yet convinced; think wobbly lines and gradients instead of straight lines and simple color schemes.
Relative positioning
Because #container has a relative position, #footer will always remain at its bottom; since the min-height mentioned above does not prevent #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer.
Padding-bottom
Since it is no longer in the normal flow, padding-bottom of #content now provides the space for the absolute #footer. This padding is included in the scrolled height by default, so that the footer will never overlap the above content.
Scale the text size a bit or resize your browser window to test this layout.
html,body {
margin:0;
padding:0;
height:100%; /* needed for container min-height */
background:gray;
font-family:arial,sans-serif;
font-size:small;
color:#666;
}
h1 {
font:1.5em georgia,serif;
margin:0.5em 0;
}
h2 {
font:1.25em georgia,serif;
margin:0 0 0.5em;
}
h1, h2, a {
color:orange;
}
p {
line-height:1.5;
margin:0 0 1em;
}
div#container {
position:relative; /* needed for footer positioning*/
margin:0 auto; /* center, not in IE5 */
width:750px;
background:#f0f0f0;
height:auto !important; /* real browsers */
height:100%; /* IE6: treaded as min-height*/
min-height:100%; /* real browsers */
}
div#header {
padding:1em;
background:#ddd url("../csslayout.gif") 98% 10px no-repeat;
border-bottom:6px double gray;
}
div#header p {
font-style:italic;
font-size:1.1em;
margin:0;
}
div#content {
padding:1em 1em 5em; /* bottom padding for footer */
}
div#content p {
text-align:justify;
padding:0 1em;
}
div#footer {
position:absolute;
width:100%;
bottom:0; /* stick to bottom */
background:#ddd;
border-top:6px double gray;
}
div#footer p {
padding:1em;
margin:0;
}
У меня отлично работает.
В этом примере в IE7 пытались увеличить размер шрифта (Ctrl + "+") и испортили липкий нижний колонтитул :(
этот, похоже, не работает в IE9 ... он работает в других IE?
Ответ kleolb02 выглядит неплохо. другой способ - комбинация липкий нижний колонтитул и минимальная высота
Чистое решение CSS (#content { min-height: 100%; }) будет работать во многих случаях, но не во всех, особенно IE6 и IE7.
К сожалению, вам придется прибегнуть к решению JavaScript, чтобы добиться желаемого поведения.
Это можно сделать, вычислив желаемую высоту для вашего контента <div> и установив ее как свойство CSS в функции:
function resizeContent() {
var contentDiv = document.getElementById('content');
var headerDiv = document.getElementById('header');
// This may need to be done differently on IE than FF, but you get the idea.
var viewPortHeight = window.innerHeight - headerDiv.clientHeight;
contentDiv.style.height =
Math.max(viewportHeight, contentDiv.clientHeight) + 'px';
}
Затем вы можете установить эту функцию в качестве обработчика событий onLoad и onResize:
<body onload = "resizeContent()" onresize = "resizeContent()">
. . .
</body>
Вы можете попробовать это: http://www.monkey-business.biz/88/horizontal-zentriertes-100-hohe-css-layout/ Это 100% высота и горизонтальный центр.
Попробуй это:
body{ height: 100%; }
#content {
min-height: 500px;
height: 100%;
}
#footer {
height: 100px;
clear: both !important;
}
Элемент div под блоком содержимого должен иметь clear:both.
Чтобы установить произвольную высоту, привязанную к чему-то:
body, html {
height: 100%;
}
#outerbox {
width: 100%;
position: absolute; /* to place it somewhere on the screen */
top: 130px; /* free space at top */
bottom: 0; /* makes it lock to the bottom */
}
#innerbox {
width: 100%;
position: absolute;
min-height: 100% !important; /* browser fill */
height: auto; /*content fill */
}<div id = "outerbox">
<div id = "innerbox"></div>
</div>просто поделитесь тем, что я использовал, и отлично работает
#content{
height: auto;
min-height:350px;
}
Я согласен с Левиком, поскольку родительский контейнер установлен на 100%, если у вас есть боковые панели и вы хотите, чтобы они заполняли пространство, чтобы встретиться с нижним колонтитулом, вы не можете установить их на 100%, потому что они также будут на 100 процентов от родительской высоты, которая также означает, что нижний колонтитул сдвигается вниз при использовании функции очистки.
Подумайте об этом так, если ваш заголовок имеет высоту 50 пикселей, а нижний колонтитул - 50 пикселей, а содержимое просто автоматически соответствует оставшемуся пространству, например, 100 пикселей, а контейнер страницы составляет 100% от этого значения, его высота будет 200 пикселей. Затем, когда вы устанавливаете высоту боковой панели на 100%, она составляет 200 пикселей, даже если предполагается, что она плотно прилегает к верхнему и нижнему колонтитулам. Вместо этого он составляет 50 пикселей + 200 пикселей + 50 пикселей, поэтому страница теперь имеет размер 300 пикселей, потому что боковые панели имеют ту же высоту, что и контейнер страницы. В содержимом страницы будет большое белое пространство.
Я использую Internet Explorer 9, и это то, что я получаю при использовании этого 100% метода. Я не пробовал использовать его в других браузерах и предполагаю, что он может работать и в некоторых других вариантах. но он не будет универсальным.
Сначала вы должны создать div с id='footer' после вашего div content, а затем просто сделать это.
Ваш HTML должен выглядеть так:
<html>
<body>
<div id = "content">
...
</div>
<div id = "footer"></div>
</body>
</html>
И CSS:
html, body {
height: 100%;
}
#content {
height: 100%;
}
#footer {
clear: both;
}
Чтобы min-height правильно работал с процентами, при наследовании своего родительского узла min-height, хитрость будет заключаться в том, чтобы установить высоту родительского узла на 1px, и тогда min-height дочернего узла будет работать правильно.
Хорошо НО, если содержимое div в демонстрации имеет большую высоту, чем окно браузера, фон будет обрезан после прокрутки вниз
@fider - предоставьте игровую площадку, показывающую проблему, которую вы упомянули.
Этот небольшой фрагмент CSS делает "the middle content part fill 100% of the space in between with the footer fixed to the bottom":
html, body { height: 100%; }
your_container { min-height: calc(100% - height_of_your_footer); }
единственное требование - иметь нижний колонтитул фиксированной высоты.
Например, для этого макета:
<html><head></head><body>
<main> your main content </main>
</footer> your footer content </footer>
</body></html>
вам нужен этот CSS:
html, body { height: 100%; }
main { min-height: calc(100% - 2em); }
footer { height: 2em; }
Как упоминалось в ответе Афшина Мехрабани, вы должны установить высоту тела и html на 100%, но чтобы получить там нижний колонтитул, рассчитайте высоту оболочки:
#pagewrapper{
/* Firefox */
height: -moz-calc(100% - 100px); /*assume i.e. your header above the wrapper is 80 and the footer bellow is 20*/
/* WebKit */
height: -webkit-calc(100% - 100px);
/* Opera */
height: -o-calc(100% - 100px);
/* Standard */
height: calc(100% - 100px);
}
Вот еще одно решение, основанное на vh или viewpoint height, подробности на сайте Единицы CSS. Он основан на решение, который вместо этого использует flex.
* {
/* personal preference */
margin: 0;
padding: 0;
}
html {
/* make sure we use up the whole viewport */
width: 100%;
min-height: 100vh;
/* for debugging, a red background lets us see any seams */
background-color: red;
}
body {
/* make sure we use the full width but allow for more height */
width: 100%;
min-height: 100vh; /* this helps with the sticky footer */
}
main {
/* for debugging, a blue background lets us see the content */
background-color: skyblue;
min-height: calc(100vh - 2.5em); /* this leaves space for the sticky footer */
}
footer {
/* for debugging, a gray background lets us see the footer */
background-color: gray;
min-height:2.5em;
}<main>
<p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
</main>
<footer>
<p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>
<p>This is the footer.</p>
</footer>The units are vw , vh, vmax, vmin. Basically, each unit is equal to 1% of viewport size. So, as the viewport changes, the browser computes that value and adjusts accordingly.
Вы можете найти дополнительную информацию здесь:
Specifically:
1vw (viewport width) = 1% of viewport width 1vh (viewport height) = 1% of viewport height 1vmin (viewport minimum) = 1vw or 1vh, whatever is smallest 1vmax (viewport minimum) = 1vw or 1vh, whatever is largest
Вы могли бы рассмотреть
min-height: 100vh;. Это устанавливает высоту, равную размеру экранаvh: vertical heightили превышающую ее. Подробнее: w3schools.com/cssref/css_units.asp.