простая высота css - PullRequest
       1

простая высота css

3 голосов
/ 16 февраля 2011

Застрял при попытке заставить элемент на веб-сайте вести себя так:

<div class="for100procHeight">
  <div class="header">fixed top</div>
  <div class="content">long text with scrolling content</div>
  <div class="footer">fixed bottom</div>
</div>

Быстрое напоминание о высоте CSS:

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

Оптимистичное решение было:

.for100procHeight { height: 100%; }
.header, .footer { height: 20px; }
.content { height:100%; overflow:scroll; }
/* failed badly: footer didn't fit into the window (heightwise) */

С уменьшенным оптимизмом была предпринята другая попытка:

<div class="for100procHeight">
  <div class="header">fixed top</div>
  <div class="footer">fixed bottom</div>
  <div class="wrapper">
    <div class="content">long text with scrolling content</div>
  </div>
</div>

.for100procHeight { height: 100%; }
.header, .footer { position: absolute; height: 20px; }
.content { height:100%; overflow:scroll; }
.header { top: 0px; left: 0px; }
.footer { bottom: 0px; left: 0px; }
.wrapper { padding-top: 20px; padding-bottom: 20px; }
/* failed badly: scroll down arrow was behind footer */
/* failed badly: scroll down arrow didn't fit into the window (heightwise) */

Это выглядит почти так, как должно, за исключением того, что высота равна 100% окна браузера (в результате чего нижняя часть элемента оказывается за пределами видимой области) .Margins / Paddings / Wrappers / etc не меняют это.

Я рассмотрел Сложную высоту в CSS , однако поддержка JS для высоты клиента / элемента выглядит еще более увлекательной.

Редактировать:

Копировать вставку из complex-height-in-css с расширением

---------------------------------------
| fixed top |   | fixed top |        |
|-----------|   |-----------|        |
|  long   |^|   |  long   |^|        |
|  text   |_|   |  text   |_|        |
|  with   |_|   |  with   |_|        |
|scrolling| |   |scrolling| |        |
| content | |   | content | |        |
|-----------|   |-----------|        |
| fixed bott|   | fixed bott|        |
--------------------------------------

Я понимаю, что наличие двух из них не было упомянуто, но и не былоимея <div class="for100procHeight"> в качестве содержимого всей страницы.

Решение:

<html>
<head>
    <style>
    html, body {
        height: 100%;
        margin: 0px;
        padding: 0px;
        overflow: hidden;
    }
    .page {
        position: absolute;
        height: 100%;
        width: 100%;
    }
    .content {
        width: 100%;
        height: 100%;
        overflow: scroll;
        overflow-x: hidden;
    }
    .content .inner {
        padding-top: 30px;
        padding-bottom: 30px;
    }
    .top {
        width: 100%;
        margin-left: -17px;
        position: absolute;
        top: 0px;
        left: 0px;
        height: 30px;
        background: url('background.gif');
    }
    .bottom {
        width: 100%;
        margin-left: -17px;
        position: absolute;
        left: 0px;  
        bottom: 0px;
        height: 30px;
        background: url('background.gif');
    }
    .top span, .bottom span {
        padding-left: 17px;
        z-index: 2000;
    }
    .top span, .bottom span {
        display: block;
        width: 100%;
    }

    #list2.page {
        margin-left: 110%;
    }
    </style>
</head>
<body>
    <div id="list1" class="page">
        <div class="top"><span>top</span></div>
        <div class="bottom"><span>bottom</span></div>
        <div id="listContent" class="content">
            <a id="page1" name="page1" style="width:1px;"></a>
            <div class="inner">
            ...
            </div>
        </div>
    </div>
    <div id="list2" class="page">
        <div class="top"><span>top</span></div>
        <div class="bottom"><span>bottom</span></div>
        <div id="listContent" class="content">
            <a id="page2" name="page2" style="width:1px;"></a>
            <div class="inner">
            ...
            </div>
        </div>
    </div>
</body>
</html>

Ответы [ 2 ]

1 голос
/ 16 февраля 2011

Дайте мне знать, если я неправильно понял, что вы ищете, но как насчет чего-то вроде этого:

CSS

* {
    margin: 0px;
    padding: 0px;
}
html, body {
    height: 100%;
}
#wrapper {
    position: relative;
    min-height: 100%;   
}
#header {
    border: 1px solid #e3e3e3;
    position: relative;
    top: 0px;
    left: 0px;
}
#footer {
    border: 1px solid #e3e3e3;
    position: relative;
    margin-top: -20px; /* negative value of footer height */
    height: 20px;
    clear:both;
}
#content {
    overflow: auto;
    padding-bottom: 20px;
    padding-left: 20px;
}

Чтобы это работало для IE, вам понадобится условие в разделе <head> для передачи этого стиля в IE 6 и ниже и в 8 и выше.

<!--[if !IE 7]>
    <style type="text/css">
        #wrapper {display:table;height:100%}
    </style>
<![endif]-->

... и исправление Opera:

body:before {
   content:"";
   height:100%;
   float:left;
   width:0;
   margin-top:-32767px;
}

HTML

<div id="wrapper">
    <div id="header">header</div>
    <div id="content">
         <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
</div>
<div id="footer">footer</div>

... посмотрите демонстрацию jsFiddle и демонстрацию с прокруткой контента . Обратите внимание, что в моем первом примере есть полоса прокрутки, потому что jsFiddle вставляет padding: 10px; в тело iFrame, содержащее демонстрацию, которую я не могу перезаписать.

Вот несколько справочных источников о «липком нижнем колонтитуле» и других полезных материалах:

Если я неправильно понял, что вы ищете, то, может быть, это лучший пример?

... и учебник по этому вопросу

Надеюсь, это поможет. Дайте мне знать, если у вас есть вопросы.

1 голос
/ 16 февраля 2011

См. Ниже код и оформить рабочий раствор на http://jsfiddle.net/SyHd9/4/

Совместимость с различными браузерами

<div class="for100procHeight">
    <div class="header">fixed top</div>
    <div class="content">long text with scrolling content</div>       
</div>
<div class="footer">fixed bottom</div>

html { height: 100%; }
body { min-height: 100%; height: 100%; }

.for100procHeight{
    position:relative;
    width:900px;
    height:100%;
    * html height:100%;
    background-color:#ccc;
}
.header{
    width:100%;
    height:100px;
    background-color:red;
    clear:both;
}
.content{
    width:100%;
    clear:both;
}
.footer{
    width:900px;
    height:100px;
    background-color:blue;
    clear:both;
}
p{
padding:10px;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...