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

Как сделать <div> всегда полный экран?

Независимо от того, как выглядит его содержимое.

Можно ли это сделать?

4b9b3361

Ответ 1

Это всегда работает для меня:

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
        html, body {
            height: 100%;
            margin: 0;
        }

        #wrapper {
            min-height: 100%; 
        }
    </style>
    <!--[if lte IE 6]>
    <style type="text/css">
        #container {
            height: 100%;
        }
    </style>
    <![endif]-->
</head>

<body>
    <div id="wrapper">some content</div>
</body>

Это, наверное, самое простое решение этой проблемы. Нужно всего лишь установить четыре атрибута CSS (хотя один из них только для того, чтобы сделать IE счастливым).

Ответ 2

Это мое решение для создания полноэкранного div, используя чистый css. Он отображает полноэкранный div, который является постоянным при прокрутке. И если содержимое страницы подходит для экрана, на странице не будет отображаться полоса прокрутки.

Протестировано в IE9 +, Firefox 13+, Chrome 21 +

<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title> Fullscreen Div </title>
  <style>
  .overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    background: rgba(51,51,51,0.7);
    z-index: 10;
  }
  </style>
</head>
<body>
  <div class='overlay'>Selectable text</div>
  <p> This paragraph is located below the overlay, and cannot be selected because of that :)</p>
</body>
</html>

Ответ 3

Это самый стабильный (и простой) способ сделать это, и он работает во всех современных браузерах:

.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: auto;
  background: lime; /* Just to visualize the extent */
  
}
<div class="fullscreen">
  Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa.
</div>

Ответ 4

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

Процентная длина видового экрана зависит от длины самого окна просмотра. Здесь мы будем использовать vh (высота видового экрана) и vw (ширина видового экрана). 100vh равно 100% высоты окна просмотра, а 100vw равно 100% ширины окна просмотра.

Предполагая следующий HTML:

<body>
    <div></div>
</body>

Вы можете использовать следующее:

html, body, div {
    /* Height and width fallback for older browsers. */
    height: 100%;
    width: 100%;

    /* Set the height to match that of the viewport. */
    height: 100vh;

    /* Set the width to match that of the viewport. */
    width: 100vw;

    /* Remove any browser-default margins. */
    margin: 0;
}

Вот демонстрация JSFiddle, которая показывает элемент div, заполняющий как высоту, так и ширину кадра результата. Если вы измените размер кадра результата, элемент div будет соответствующим образом изменен.

Ответ 5

У меня нет IE Josh, не могли бы вы проверить это для меня. Спасибо.

<html>
<head>
    <title>Hellomoto</title>
    <style text="text/javascript">
        .hellomoto
        {
            background-color:#ccc;
            position:absolute;
            top:0px;
            left:0px;
            width:100%;
            height:100%;
            overflow:auto;
        }
        body
        {
            background-color:#ff00ff;
            padding:0px;
            margin:0px;
            width:100%;
            height:100%;
            overflow:hidden;
        }
        .text
        {
            background-color:#cc00cc;
            height:800px;
            width:500px;
        }
    </style>
</head>
<body>
<div class="hellomoto">
    <div class="text">hellomoto</div>
</div>
</body>
</html>

Ответ 6

То, что я нашел, лучший изящный способ выглядит следующим образом, самый трюк здесь - сделать div position: fixed.

.mask {
    background-color: rgba(0, 0, 0, 0.5);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: 0;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    object-fit: contain;
}
<html>
  <head>
  <title>Test</title>
  </head>
  <body>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <h1>Whatever it takes</h1>
    <div class="mask"></div>
    </body>
  </html>

Ответ 7

Измените элемент body на flex container и div на flex item:

body {
  display: flex;
  height: 100vh;
  margin: 0;
}

div {
  flex: 1;
  background: tan;
}
<div></div>

Ответ 8

Здесь самое короткое решение, основанное на vh. Обратите внимание, что vh не поддерживается в некоторых старых браузерах.

CSS:

div {
    width: 100%;
    height: 100vh;
}

HTML:

<div>This div is fullscreen :)</div>

Ответ 9

Это трюк, который я использую. Хорошо подходит для гибких конструкций. Прекрасно работает, когда пользователь пытается изменить размер браузера.

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
        #container {
            position: absolute;
            width: 100%;
            min-height: 100%;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div id="container">some content</div>
</body>

Ответ 10

К сожалению, свойство height в CSS не так надежно, как должно быть. Поэтому Javascript должен использоваться для установки стиля высоты рассматриваемого элемента на высоту окна просмотра пользователей. И да, это можно сделать без абсолютного позиционирования...

<!DOCTYPE html>

<html>
  <head>
    <title>Test by Josh</title>
    <style type="text/css">
      * { padding:0; margin:0; }
      #test { background:#aaa; height:100%; width:100%; }
    </style>
    <script type="text/javascript">
      window.onload = function() {
        var height = getViewportHeight();

        alert("This is what it looks like before the Javascript. Click OK to set the height.");

        if(height > 0)
          document.getElementById("test").style.height = height + "px";
      }

      function getViewportHeight() {
        var h = 0;

        if(self.innerHeight)
          h = window.innerHeight;
        else if(document.documentElement && document.documentElement.clientHeight)
          h = document.documentElement.clientHeight;
        else if(document.body) 
          h = document.body.clientHeight;

        return h;
      }
    </script>
  </head>
  <body>
    <div id="test">
      <h1>Test</h1>
    </div>
  </body>
</html>