我通過輸入「margin-left:12%」來設置水平居中div(id =「div_below_nav」)。據我所知,divs通常是使用「margin-left:auto」來水平居中的。&「margin-right:auto」。我試過了,但是div一路轉移到左邊。我很困惑,爲什麼會發生這種情況,如果有人能爲我解釋,我會很高興。爲什麼我必須輸入「margin-left:12%」來居中我的div?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CLC Website</title>
<link rel="stylesheet" href="main3.css">
</head>
<body>
<div id="header">
<div id="nav">
<img src="../images/logo.png" id="logo" alt="logo">
<p id="logo_text">CLC</p>
<ul>
<li><a href="#">Contact Us</a></li>
<li><a href="#">Professors</a></li>
<li><a href="#">Courses</a></li>
<li><a href="#">About</a></li>
</ul>
</div>
<div id="welcome_text_div">
<p id="welcome_text">The Best Offer</p>
<p id="welcome_under_text">Truth evades a single definition and true
understanding requires a comparative perspective</p>
</div>
<div id="div_below_nav">
<p></p>
</div>
</div>
</body>
</html>`
MY CSS:
body {
margin: 0;
background-color: #e7e5e5;
}
ul {
margin-top: -50px;
}
li {
float: right;
font-weight: bold;
}
li a {
display: block;
text-decoration: none;
text-align: center;
font-family: sans-serif;
color: white;
border-right: 1px solid white;
padding: 8px;
}
li a:visited {
text-decoration: none;
color: white;
font-family: sans-serif;
}
li a:hover:not(.active) {
background-color: #333;
}
#header {
position: relative;
width: 100%;
height: 600px;
background-image: url('bg.jpg');
background-repeat: no-repeat;
background-size: 100% 100%;
}
#nav {
position: absolute;
width: 100%;
height: 50px;
}
#logo {
width: 50px;
height: 50px;
}
#logo_text {
position: absolute;
display: inline;
top: -9px;
left: 55px;
font-size: 20px;
font-family: sans-serif;
color: white;
font-weight: bold;
}
#welcome_text_div {
position: absolute;
width: 800px;
height: 300px;
top: 50%;
margin-top: -150px;
left: 50%;
margin-left: -400px;
}
#welcome_text {
color: white;
font-family: sans-serif;
text-transform: uppercase;
font-weight: bold;
font-size: 60px;
text-align: center;
}
#welcome_under_text {
color: white;
font-family: sans-serif;
text-align: center;
font-weight: bold;
margin-top: -50px;
}
#div_below_nav {
position: absolute;
width: 950px;
height: 300px;
margin-top: 650px;
margin-bottom: 50px;
background-color: red;
margin-left: 12%;
}`
Divs通常使用'margin:0 auto;'居中。 –
當我這樣做,然後我的div進入屏幕的最左上角。 – noddy
嘗試保證金的左右自動沒有絕對定位 – Pete