[英]How do I center a div and make it expand around the divs inside of it?
我有一個我想要居中的頁面,背景和整個內容的邊框。
我做了一個div並用背景顏色和我想要的邊框設置來設置它。
問題是它里面的div有浮動而背景不會在浮動div周圍伸展。 我能夠讓它工作的唯一方法是設置position:absolute。 然后邊界確實在浮動div周圍擴展,但我無法使用常規html / css將它們居中。
我找到了一個javascript hack來使它成為中心,但它只在頁面加載后居中並且看起來很糟糕。
我確信有一種方法可以讓容器擴展並使其居中,我只是想不出來。
這是一個分享我的問題的示例html頁面
<div style="background-color: Red; width: 980px; position: absolute;" id="container">
<br />
<br />
<br />
<br />
<div style="width: 400px; background-color: Black; float: left;">
<br />
<br />
</div>
<div style="width: 400px; background-color: Blue; float: left;">
<br />
<br />
</div>
</div>
這是使它工作的Javascript(使用Jquery)
$(function() {
var winH = $(window).height();
var winW = $(window).width();
$("#container").css('left', winW / 2 - $("#container").width() / 2);
});
必須有一個更好的方法。
謝謝
使用auto
作為左右margin
以使元素居中。
在浮動元素后放置一個元素,並使用clear
將其放在它們下面。 由於它不是浮動的,它會影響外部div的大小。
<div style="margin: 0 auto; background-color: Red; width: 980px;" id="container">
<br />
<br />
<br />
<br />
<div style="width: 400px; background-color: Black; float: left;">
<br />
<br />
</div>
<div style="width: 400px; background-color: Blue; float: left;">
<br />
<br />
</div>
<div style="clear: both; height: 0; overflow: hidden;"></div>
</div>
這是一個棘手的問題,但我在樣式表中使用了以下代碼;
<style>div.sentor {text-align: center; height: 100%;} div.child{margin-left: auto; margin-right: auto; width: 95%; height: 100%;}</style>
然后在體內;
<div class="sentor">
<div class="child">
<div id="mycontent">
這應該可以解決問題
也許我不能很好地理解你的問題,但我認為你正在尋找類似的東西。 這是我們簡單的布局:
<html>
<head>
...
</head>
<body>
<div id="center">
<!-- your content -->
</div>
</body>
</html>
要使div#center的內容移動到頁面的中心,我們需要以下CSS:
body {
text-align: center;
}
div#center {
text-align: left;
width: 600px; // Or some other arbitrary width
margin: 0 auto;
}
這將把所有內容集中在體內。 但是,text-align:center; 屬性也將適用於身體的孩子,所以我們用第二個樣式規則取消了。 或者,您可以使用以下樣式規則代替div#center:
body * {
text-align: left;
}
使用:
<div style="margin:0 auto; overflow:hidden; background-color: Red; width: 980px; id="container">
保證金:0自動; 將紅色div居中。
溢出:隱藏; 將使紅色div拉伸包含兩個浮動div。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.