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

Как сделать высоту div для заполнения свободного места

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

enter image description here

Вы заметите, что одна из высоты столбца больше, чем остальные. Я бы хотел, чтобы два других divs автоматически заполнили оставшееся пространство (до синего div). Текст будет загружен динамически, поэтому мне нужно, чтобы он работал с любым столбцом, большим (и произвольной суммой).

Можно ли это сделать с помощью HTML/CSS или мне нужно использовать какой-то JavaScript?


HTML-код (соответствующая его часть):

<div id="content">

    <div id="iconsHolder">

        <div id="info">
            <div id="info_content">
                <p><?php echo img('images/man.png'); ?></p>
                <h2>Some guy over here</h2>
                <p class="light justify">It doesn't matter what is being said at the moment. Nothing is said here.</p>
            </div>
        </div>

        <div id="comp">
            <div id="comp_content">
                <p><?php echo img('images/computer.png'); ?></p>
                <h2>Computer Development</h2>
                <p class="light justify">Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...</p>
            </div>
        </div>

        <div id="story">
            <div id="story_content">
                <p><?php echo img('images/library.png'); ?></p>
                <h2>Story telling</h2>
                <p class="light justify">This is another short story.</p>
            </div>
        </div>
    </div>
    <div id="details">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>

</div>

CSS-код (соответствующая его часть):

#content {
    width: 60em;
    margin: 0px auto;
}

#info,#comp,#story {
    width: 18em;
    float: left;
    padding-left: 1em;
    padding-right: 1em;
    padding-top: 2em;
    background-color: #DDD;
    height: 100%;
}

#info_content,#comp_content,#story_content {
    text-align: center;
}

#details {
    clear: both;
    background-color: #EEF;
    padding: 1em;
}
4b9b3361

Ответ 1

Решение CSS - это стиль внешнего контейнера с цветом фона, это называется подделкой (faux) bakcground.

Вот так:

#iconsHolder {
    background-color: #DDD;
}

Этот метод (в этом случае, по крайней мере) гарантирует, что фон для всех одинаковый.

Ответ 2

Вместо того, чтобы плавать divs, вы можете полностью позиционировать их в div#iconsHolder (что вы сделаете position:relative. Вы все равно устанавливаете ширину, просто установите левую часть каждого div на соответствующее смещение и дайте каждому top:0 и bottom:0 правил CSS.

Ответ 3

Подход, который вы сделали, очень запутан и затрудняет управление CSS. Если вы преобразуете его в таблицу, у вас будут лучшие результаты.

<table id="content" cellspacing="0">
<tr id="row">
<div id="iconsHolder">

    <td id="info">
        <div id="info_content">
            <p><?php echo img('images/man.png'); ?></p>
            <h2>Some guy over here</h2>
            <p class="light justify">It doesn't matter what is being said at the moment. Nothing is said here.</p>
        </div>
    </td>

    <td id="comp">
        <div id="comp_content">
            <p><?php echo img('images/computer.png'); ?></p>
            <h2>Computer Development</h2>
            <p class="light justify">Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...</p>
        </div>
    </td>

    <td id="story">
        <div id="story_content">
            <p><?php echo img('images/library.png'); ?></p>
            <h2>Story telling</h2>
            <p class="light justify">This is another short story.</p>
        </div>
    </td>
</div>
</tr>
    <tr id="bottom">
<td id="details" colspan="3">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</td>
    </tr>
</table>

Затем вам нужно удалить float:left; из строки 8 вашего CSS и вставить этот код внизу.

tr#row td {
    width: 30%;
    background-color: #DDD;
    vertical-align: top;
}

Ответ 4

Довольно простое решение состоит в том, чтобы сделать идентификатор контейнера div в виде фона следующим:

#iconsHolder { background-color: #DDD; float:left;}

Добавьте это к вашему css и он должен работать во всех браузерах.

Ответ 5

В дополнение к добавлению цвета фона в контейнер, вам также потребуется сделать контейнер занимать пространство детей.

Вы можете добавить float:left в контейнер, например ответ Ричарда или Если вы не хотите, чтобы контейнер плавал, вы можете добавить пустой "ясный" div после этого. Это менее семантически корректно, но если вы не можете или не хотите, чтобы контейнер плавал, это еще один вариант.

JsFiddle: http://jsfiddle.net/gvJrJ/4/

Ответ 6

В настоящее время ваши столбцы охватывают насколько текст может идти. Если я правильно задаю ваш вопрос, вы хотели бы, чтобы цвет фона/столбца столбцов превышал доступные данные. Если это то, что вы хотите, тогда вам нужно создать поддельные столбцы (столбцы искусственного интеллекта), так как ваши данные в этих столбцах не охватывают всю высоту.

Я думаю, что самый простой способ - применить повторяющееся обратное изображение к элементу WHICH, который охватывает всю высоту вашего счета. Это может быть своего рода оболочка, которая охватывает ваши столбцы. В вашем случае вы можете применить тонкое изображение, которое будет разделено на три цветовые полосы (по одному на каждый, каждый из которых будет отображаться для конкретного столбца) для информационных, comp и сюжетных div. Это изображение будет шириной 60 м и будет повторяться по оси y, например:

#content 
{
background: #ccc url(fake-columns.gif) repeat-y left top;
}

Предполагается, что изображение находится в той же папке, что и файл css (не рекомендуется, images/fake-columnss.gif лучше, чтобы изображение ссылалось на папку с изображением). Повтор-y повторит крошечный снимок вниз, покрывая всю высоту содержимого содержимого. Левый верх гарантирует, что изображение начнет черепицей из верхнего левого угла, что вы обычно хотели бы сделать! Символ фунта перед контентом, кажется, исчезает из моего примера css выше.

Ответ 7

Можно ли это сделать с помощью HTML/CSS или сделать это? нужно использовать JavaScript?

.. это можно сделать с помощью чистого CSS с помощью display: table-cell.. но нет поддержки iE7 и ниже: (

Здесь решение, использующее оба метода (jQuery * и CSS), jQuery, конечно, сделает то же самое для других браузеров, но это решение означает, что большинство пользователей получат чистое решение CSS только с IE7 и ниже jQuery для "улучшения"

если вы хотите использовать решение jQuery для всех браузеров, тогда вам не понадобятся свойства отображения table-cell или table-row, и вам нужно будет удалить хакер !ie7 из свойства float - поплавки также понадобятся чтобы он содержал кросс-браузер, поэтому вы можете добавить overflow: hidden в div #iconsHolder и просто оставить zoom: 1; на месте, если вам нужно, чтобы он работал в IE6;)

CSS

#content {
    width: 60em;
    margin: 0px auto;
}

#iconsHolder { 
    display: table-row; /* good browsers - IE7 and below ignore this */
    zoom: 1; /* for IE to contain the floats so the jQuery can get a height from it */
    /* overflow: hidden; would be needed here if jQuery solution is preferrred */
}

#info,#comp,#story {
    width: 18em;
    padding-left: 1em;
    padding-right: 1em;
    padding-top: 2em;
    background-color: #DDD;
    display: table-cell;
    float: left !ie7; /* IE7 and below hacked value - remove the !ie7 part to expose this to all browsers */ 
}

#info_content,#comp_content,#story_content {
    text-align: center;
}

#details {
    clear: both;
    background-color: #EEF;
    padding: 1em;
}

HTML:

<div id="content">
 <div id="iconsHolder">
  <div id="info">
    <div id="info_content">
     <p><img src="http://placekitten.com/100/100/" alt=""></p>
     <h2>Some guy over here</h2>
     <p class="light justify">It doesn't matter what is being said at the moment. Nothing is said here.</p>
    </div>
   </div>
   <div id="comp">
    <div id="comp_content">
     <p><img src="http://placekitten.com/100/100/" alt=""></p>
     <h2>Computer Development</h2>
     <p class="light justify">Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...</p>
    </div>
   </div>
   <div id="story">
    <div id="story_content">
     <p><img src="http://placekitten.com/100/100/" alt=""></p>
     <h2>Story telling</h2>
     <p class="light justify">This is another short story.</p>
    </div>
  </div>
 </div>

  <div id="details">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</div>

jQuery: (внутри условного комментария, поэтому только IE7 и ниже см. его)

<!--[if lte IE 7]>
<script type="text/javascript">
$(document).ready(function() {

    var divHeight = $("#iconsHolder").outerHeight();          
    $("#iconsHolder > div").css("height", divHeight);

});
</script>
<![endif]-->

Добавлено: JSfiddle

Примечание: скрипта не содержит jQuery, поскольку я не знаю, как это сделать в условном комментарии к скрипке)


  • Прошу прощения, если вы предпочтете чистое решение для JavaScript, я не могу этого сделать, но я уверен, что если вы хотите, чтобы кто-то мог добавить чистый JS к моему ответу за вас!

Ответ 8

Как вы сказали, проблема с использованием фона с вашим #iconHolder выделяет каждый столбец при наведении курсора мыши.

Итак, вот что я предлагаю:

1) сделайте отдельные столбцы faux абсолютно позиционированными в том же месте, что и исходный столбец

Вы будете использовать свойство z-index, чтобы убедиться, что контент находится сверху

HTML

<div id="col1"></div>
<div id="col2"></div>
<div id="col3"></div>

<div id="faux1"></div>
<div id="faux2"></div>
<div id="faux3"></div>

CSS

#iconHolder {
    position: relative;
}

#col1, #col2, #col3 {
    position: relative
    z-index: 100;
}

#faux1, #faux2, #faux3 {
    position: absolute;
    top: 0;
    bottom: 0;
    background-color: #DDD /* don't add a background to your real columns, just your faux */
    z-index: 50;
}

#faux2 {
    left: 20em;
}

#faux3 {
    left: 40em;
}

2) присоединяйте события onmouseover/onclick как к столбцу faux, так и к нормальному столбцу

function highlight() {
     faux.style.backgroundColor = "yellow"
}

function whatever() {
    //your code here
}

column.onmousover = highlight
faux.onmouseover = highlight
column.onclick = whatever
faux.onclick = whatever

Если вам нужна более подробная информация о javascript, просто спросите, я просто не имел бы представления об эквиваленте jQuery.

Да, я понимаю, что это немного хаки, но он выполняет свою работу без вычисления высоты или чего-то еще. Надеюсь, это поможет!