Подтвердить что ты не робот

Flexbox и единицы высоты vh не совместимы в IE11?

Я пытаюсь использовать макет на основе flexbox, чтобы получить липкий нижний колонтитул для моей страницы. Это хорошо работает в Chrome и Firefox, но в IE11 нижний колонтитул находится сразу после моего основного контента. Другими словами, основной контент не растягивается, чтобы заполнить все доступное пространство.

body {
    border: red 1px solid;
    min-height: 100vh;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -ms-flex-direction: column;
    -webkit-flex-direction: column;
    flex-direction: column;
}
header, footer  {
    background: #dd55dd;
}
main {
    background: #87ccfc;
    -ms-flex: 1 0 auto;
    -webkit-flex: 1 0 auto;
    flex: 1 0 auto;
}
<body>
    <header role="banner"><h1> .. </h1></header>
    <main role="main">
        <p>.....</p>
    </main>
    <footer>...</footer>
</body>
4b9b3361

Ответ 1

Проблема не в единицах vh, а min-height

Я нашел полурабочее решение только для CSS:

min-height: 100vh;
height: 100px;

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


Так как этого недостаточно, я сделал решение в JS:

Обнаружение

Эта функция проверяет ошибку: true означает, что она не работает.

function hasBug () {
    // inner should fill outer
    // if inner height is 0, the browser has the bug

    // set up
    var outer = document.createElement('div');
    var inner = document.createElement('div');
    outer.setAttribute('style', 'display:-ms-flexbox; display:flex; min-height:100vh;');
    outer.appendChild(inner);
    (document.body || document.documentElement).appendChild(outer);

    // test
    var bug = !inner.offsetHeight;

    // remove setup
    outer.parentNode.removeChild(outer);

    return bug;
}

Fix

Исправление состоит из ручной установки height элемента в px

function fixElementHeight (el) {
    // reset any previously set height
    el.style.height = 'auto'; 

    // get el height (the one set via min-height in vh)
    var height = el.offsetHeight; 

    // manually set it in pixels
    el.style.height = height + 'px'; 
}

Высота элемента будет равна высоте его содержимого. height используется как вторичный min-height в IE, используя поведение, наблюдаемое в решении только CSS.

Использование

Как только эти две функции определены, настройте его следующим образом:

if(hasBug()) {
    // fix the element now
    fixElementHeight(el);

    // update the height on resize
    window.addEventListener('resize', function () {
        fixElementHeight(el);
    });
}

Demo

function hasBug () {
    // inner should fill outer
    // if inner height is 0, the browser has the bug

    // set up
    var outer = document.createElement('div');
    var inner = document.createElement('div');
    outer.setAttribute('style', 'display:-ms-flexbox; display:flex; min-height:100vh;');
    outer.appendChild(inner);
    (document.body || document.documentElement).appendChild(outer);

    // test
    var bug = !inner.offsetHeight;

    // remove setup
    outer.parentNode.removeChild(outer);

    return bug;
}

function fixElementHeight (el) {
    // reset any previously set height
    el.style.height = 'auto'; 

    // get el height (the one set via min-height in vh)
    var height = el.offsetHeight; 

    // manually set it in pixels
    el.style.height = height + 'px'; 
}

var output = document.getElementById('output');
output.innerHTML = hasBug()?'Browser is buggy':'Browser works correctly';


var el = document.getElementById('flex');

if(hasBug()) {
  // fix the element now
  fixElementHeight(el);

  // update the height on resize
  window.addEventListener('resize', function () {
    fixElementHeight(el);
  });
}
.half-screen {
  display:-ms-flexbox;
  display: flex;
  min-height: 50vh;

  padding: 10px;
  background: #97cef0;
}


.content {
  padding: 10px;
  background: #b5daf0;
}
The inner box should fill the outer box vertically, even if the browser is buggy.
<div class="half-screen" id="flex">
  <div class="content" id="output">
    Text
  </div>
</div>

Ответ 2

Вчера я столкнулся с этой же ошибкой и не смог решить ее сам. К сожалению, на данный момент ничего нельзя сделать, потому что это ошибка IE, о которой сообщают разработчикам Microsoft почти год назад, здесь:

https://connect.microsoft.com/IE/feedback/details/802625/min-height-and-flexbox-flex-direction-column-dont-work-together-in-ie-10-11-preview

Ответ 3

Уловка, с которой я столкнулся при работе с липкими нижними колонтитулами в IE11, заключается в том, чтобы убедиться, что flex-basis - это 100% или даже 100vh. Посмотрите приведенный ниже пример или живой пример Codepen, который вы можете протестировать в IE11.

html {
  display: flex;
  flex-direction: column;
}

body {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  flex-basis: 100%;
  min-height: 100vh;
}

header {
  padding: 32px;
  background-color: seagreen;
}

main {
  flex-grow: 1;
  padding: 32px;
  background-color: rgba(0, 0, 0, 0.05);
}

footer {
  padding: 32px;
  background-color: coral;
}
<header>
  Header
</header>
<main>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
  <p>I will not skateboard in the halls.</p>
</main>
<footer>
  Footer
</footer>

Ответ 4

Обычно это помогает:

html, body {
   height: 100%;
}

.. и вам не нужно использовать единицы vh.

Полный образец:

* {
  margin: 0;
}
html,
body {
  height: 100%;
}
body {
  border: red 1px solid;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -ms-flex-direction: column;
  -webkit-flex-direction: column;
  flex-direction: column;
}
header,
footer {
  background: #dd55dd;
}
main {
  background: #87ccfc;
  -ms-flex: 1;
  -webkit-flex: 1;
  flex: 1;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
}
<header>
  <h1>Herons - How they plan to eat your eyes!</h1>
</header>
<main>
  Herons are foul and devious birds.
</main>
<footer>
  <small>© 2014 Institute for the prevention of Herons</small>
</footer>