[英]Div container not centering with margin auto
我在將容器放在我的網站上時遇到問題。 我希望此容器居中並覆蓋大約80%的頁面。 這樣我就可以在其中放置圖像滑塊和文本。 保證金:0自動,似乎不起作用。 容器的背景色僅在position設置為absolute時顯示。 我在這里做錯了什么?
CSS
@charset "utf-8";
/* CSS Document */
#container {
top: 125px;
left: 0;
margin: 0 auto;
width: 70%;
background-color: #b0e0e6;
height: 100%;
position: absolute;
}
#header {
background-color: #2f2f2f;
height: 125px;
top: 0;
left: 0;
position: fixed;
width: 100%;
margin: none;
padding: none;
z-index: 1;
}
#footer {
background-color: #2f2f2f;
height: 30px;
bottom: 0;
left: 0;
position: fixed;
width: 100%;
margin: none;
padding: none;
z-index: 1;
}
#logo {
position: fixed;
z-index: 2;
}
#logo img {
height: 100px;
}
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="styles.css" rel="stylesheet" type="text/css" />
<title>Untitled Document</title>
</head>
<body>
<div id="logo"><img src="images/jpl101-300x254.png" /></div>
<div id="header"></div>
<div id="footer"></div>
<div id="container">
</div>
</body>
</html>
與我試圖做的相比,這就是我要完成的工作。
您已將其設置為position: absolute
,這意味着它將僅以margin: 0 auto
中心margin: 0 auto
如果您還設置了: left:0;right:0;
則為margin: 0 auto
left:0;right:0;
div { padding: 10px; background: #2d2d2d; color: #fff; font-weight: bold; text-transform: uppercase; } .center { position: absolute; margin: 0 auto; width: 70%; } .one { left:0; } .two { left:0; right:0; top: 200px; /* so you can see it */ }
<div class="center one">First</div> <div class="center two">Second</div>
確實,您似乎根本不應該使用position: absolute
。
嘗試一下(將邊距更改為百分比)
#container {
margin: 0 15%;
width: 70%;
background-color: #b0e0e6;
height: 100%;
}
您有70%的寬度,因此將剩余的30%的寬度除以2,然后從每一邊(左側和右側)除以15%,就完成了。 這是類似的東西
您只需要添加一個right:0; 到容器中,以迫使頁邊距“綁定”到屏幕右側,並自動填充頁邊距。
您需要使用margin-top
而不是position: absolute
與top
結合使用:
#container {
margin: 0 auto;
margin-top: 125px;
width: 70%;
background-color: #b0e0e6;
height: 100%;
}
基本上,這些position
和margin
並不能很好地配合。
包裝div,然后居中。
CSS:
.containerWrapper{
width: 100%;
height: 100%;
position: absolute;
}
#container {
margin: 0 auto;
width: 70%;
background-color: #b0e0e6;
height: 100%;
position: relative;
}
HTML:
<div class="containerWrapper">
<div id="container"></div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.