簡體   English   中英

HTML/CSS:使兩個浮動 div 具有相同的高度

[英]HTML/CSS: Making two floating divs the same height

我有一個小問題,我目前使用table解決,見下文。 基本上,我想讓兩個 div 占據可用寬度的 100%,但只占據所需的垂直空間(這在圖片中並不是那么明顯)。 如圖所示,兩者應始終具有完全相同的高度,並在它們之間留一條小線。

替代文字
(來源: pici.se

使用table很容易做到這一點,我目前正在這樣做。 但是,我不太熱衷於解決方案,因為從語義上講,這實際上不是一個表格。

您可以通過應用大量的底部填充、相同數量的底部負邊距並用隱藏溢出的 div 圍繞列來在 CSS 中獲得相等高度的列。 垂直居中文本有點棘手,但這應該對您有所幫助。

 #container { overflow: hidden; width: 100%; } #left-col { float: left; width: 50%; background-color: orange; padding-bottom: 500em; margin-bottom: -500em; } #right-col { float: left; width: 50%; margin-right: -1px; /* Thank you IE */ border-left: 1px solid black; background-color: red; padding-bottom: 500em; margin-bottom: -500em; }
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head></head> <body> <div id="container"> <div id="left-col"> <p>Test content</p> <p>longer</p> </div> <div id="right-col"> <p>Test content</p> </div> </div> </body>

我認為值得一提的是 streetpc 的先前答案具有無效的 html,文檔類型是 XHTML,並且屬性周圍有單引號。 另外值得注意的是你不需要有額外的元素clear以清除容器的內部彩車上。 如果您使用溢出隱藏這會清除所有非 IE 瀏覽器中的浮點數,然后只需添加一些內容來提供 hasLayout,例如 width 或 zoom:1 將導致 IE 清除其內部浮點數。

我已經在所有現代瀏覽器 FF3+ Opera9+ Chrome Safari 3+ 和 IE6/7/8 中對此進行了測試。 這似乎是一個丑陋的技巧,但效果很好,我在生產中經常使用它。

我希望這有幫助。

現在是 2012+n 年,所以如果你不再關心 IE6/7, display:tabledisplay:table-rowdisplay:table-cell可以在所有現代瀏覽器中工作:

http://www.456bereasttreet.com/archive/200405/equal_height_boxes_with_css/

2016 年 6 月 17更新:如果您認為display:flex時代已經到來,請查看Flexbox Froggy

您應該使用 flexbox 來實現這一點。 它在 IE8 和 IE9 中不受支持,在 IE10 中只有 -ms 前綴,但所有其他瀏覽器都支持它。 對於供應商前綴,您還應該使用autoprefixer

.parent {
    display: flex;
    flex-wrap: wrap; // allow wrapping items
}

.child {
    flex-grow: 1;
    flex-basis: 50%; // 50% for two in a row, 33% three in a row etc.
}

你可以用 js 來實現這個:

<script>
    $(document).ready(function() {
        var height = Math.max($("#left").height(), $("#right").height());
        $("#left").height(height);
        $("#right").height(height);
    });
</script>

這是 CSS 中的一個經典問題。 對此沒有真正的解決方案。

來自 A List Apart 的這篇文章很好地解釋了這個問題。 它使用一種稱為“假列”的技術,基於在包含列元素上放置一個垂直平鋪的背景圖像,從而產生等長列的錯覺。 由於它位於浮動元素的包裝器上,因此它與最長的元素一樣長。


A List Apart 編輯在文章中有這樣的注釋:

編者注:盡管在當時非常出色,但本文可能無法反映現代最佳實踐。

該技術需要完全靜態的寬度設計,不能很好地與當今跨設備站點流行的流動布局和響應式設計技術配合使用。 然而,對於靜態寬度站點,這是一個可靠的選擇。

我有類似的問題,我認為最好的選擇是只使用一點點 javascript 或 jquery。

您可以通過獲取最高 div 值並將該值應用於所有其他 div 來使想要的 div 具有相同的高度。 如果你有很多 div 和很多解決方案,我建議編寫一些高級 js 代碼來找出所有 div 中哪個是最高的,然后使用它的價值。

使用 jquery 和 2 個 div 非常簡單,這里是示例代碼:

$('.smaller-div').css('height',$('.higher-div').css('height'));

最后,還有最后一件事。 它們的填充(頂部和底部)必須相同! 如果有較大的填充,則需要消除填充差異。

這在 IE 7、FF 3.5、Chrome 3b、Safari 4 (Windows) 中對我有用。

如果您取消注釋底部更清晰的 div,也適用於 IE 6。 編輯:正如 Natalie Downe 所說,您可以簡單地添加width: 100%; 改為#container

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <style type="text/css">
        #container {
            overflow: hidden;
            border: 1px solid black;
            background-color: red;
        }
        #left-col {
            float: left;
            width: 50%;
            background-color: white;
        }
        #right-col {
            float: left;
            width: 50%;
            margin-right: -1px; /* Thank you IE */
        }
    </style>
</head>
<body>
    <div id='container'>
        <div id='left-col'>
            Test content<br />
            longer
        </div>
        <div id='right-col'>
            Test content
        </div>
        <!--div style='clear: both;'></div-->
    </div>
</body>
</html>

如果 div 的高度不固定,我不知道一種將文本垂直居中的 CSS 方法。 如果是,您可以將line-height設置為與 div 高度相同的值,並使用display: inline; line-height: 110%放置一個包含文本的內部 div display: inline; line-height: 110% display: inline; line-height: 110%

據我所知,您不能使用當前的 CSS 實現來做到這一點。 要制作兩列,等高,您需要 JS。

使用 Javascript,您可以使兩個 div 標簽具有相同的高度。 使用下面顯示的代碼,較小的 div 將調整為與最高的 div 標簽相同的高度:

var rightHeight = document.getElementById('right').clientHeight;
var leftHeight = document.getElementById('left').clientHeight;
if (leftHeight > rightHeight) {
document.getElementById('right').style.height=leftHeight+'px';
} else {
document.getElementById('left').style.height=rightHeight+'px';
}

“左”和“右”是 div 標簽的 id。

通過使用 css 屬性 --> display:table-cell

 div { border: 1px solid #000; margin: 5px; padding: 4px; display:table-cell; width:25% ;position:relative; } body{display:table; border-collapse:separate; border-spacing:5px 5px}
 <div> This is my div one This is my div one This is my div one </div> <div> This is my div two This is my div two This is my div two This is my div two This is my div two This is my div two </div> <div> This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 </div>

 div { border: 1px solid #000; margin: 5px; padding: 4px; display:table-cell; width:25% ;position:relative; } body{display:table; border-collapse:separate; border-spacing:5px 5px} 
 <div> This is my div one This is my div one This is my div one </div> <div> This is my div two This is my div two This is my div two This is my div two This is my div two This is my div two </div> <div> This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 </div> 

使用 JS,在所有要具有相同高度的元素中使用data-same-height="group_name"

例子: https : //jsfiddle.net/eoom2b82/

代碼:

$(document).ready(function() {
    var equalize = function () {
        var disableOnMaxWidth = 0; // 767 for bootstrap

        var grouped = {};
        var elements = $('*[data-same-height]');

        elements.each(function () {
            var el = $(this);
            var id = el.attr('data-same-height');

            if (!grouped[id]) {
                grouped[id] = [];
            }

            grouped[id].push(el);
        });

        $.each(grouped, function (key) {
            var elements = $('*[data-same-height="' + key + '"]');

            elements.css('height', '');

            var winWidth = $(window).width();

            if (winWidth <= disableOnMaxWidth) {
                return;
            }

            var maxHeight = 0;

            elements.each(function () {
                var eleq = $(this);
                maxHeight = Math.max(eleq.height(), maxHeight);
            });

            elements.css('height', maxHeight + "px");
        });
    };

    var timeout = null;

    $(window).resize(function () {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }

        timeout = setTimeout(equalize, 250);
    });
    equalize();
});

我需要做類似的事情,這是我的實現。 回顧一下目的,它是讓 2 個元素占據給定父容器的寬度,並且高度僅是它需要的高度。 基本上高度等於最大內容量的最大高度,但另一個容器是齊平的。

html

<div id="ven">
<section>some content</section>
<section>some content</section>
</div>

css

#ven {
height: 100%;
}
#ven section {
width: 50%;
float: left;
height: 100%;
}

幾年前, float屬性用於通過使用display: table;table方法解決該問題display: table; display: table-row; display: table-cell; .

但是現在有了 flex 屬性,就可以用 3 行代碼解決: display: flex; flex-wrap: wrap; flex: 1 0 50%;

.parent {
    display: flex;
    flex-wrap: wrap;
}

.child {
 // flex: flex-grow flex-shrink flex-basis;
    flex: 1 0 50%;
}

1 0 50%是我們賦予的flex值: flex-grow flex-shrink flex-basis分別。 這是 flexbox 中一個相對較新的快捷方式,以避免單獨輸入它們。 我希望這可以幫助那里的人

考慮到 Natalie 的回應,這似乎非常好,但是我在可能的頁腳區域方面遇到了問題,可以使用clear: both對其進行一些黑客攻擊。

當然,現在更好的解決方案是使用 flexbox 或 grid。

如果你願意,你可以檢查這個代碼筆

在此處輸入圖片說明

 .section { width: 500px; margin: auto; overflow: hidden; padding: 0; } div { padding: 1rem; } .header { background: lightblue; } .sidebar { background: lightgreen; width: calc(25% - 1rem); } .sidebar-left { float: left; padding-bottom: 500rem; margin-bottom: -500rem; } .main { background: pink; width: calc(50% - 4rem); float: left; padding-bottom: 500rem; margin-bottom: -500rem; } .sidebar-right { float: right; padding-bottom: 500rem; margin-bottom: -500rem; } .footer { background: black; color: white; float: left; clear: both; margin-top: 1rem; width: calc(100% - 2rem); }
 <div class="section"> <div class="header"> This is the header </div> <div class="sidebar sidebar-left"> This sidebar could have a menu or something like that. It may not have the same length as the other </div> <div class="main"> This is the main area. It should have the same length as the sidebars </div> <div class="sidebar sidebar-right"> This is the other sidebar, it could have some ads </div> <div class="footer"> Footer area </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM