我會假設你的意思是居中在頁面上的元素,然後添加背景顏色到那個元素。儘管您接近,但您的CSS無效。如果你想添加背景,那麼你需要使用背景顏色。如果要將該元素居中,則可以在此處調整該元素的邊距。是一個可能有所幫助的例子。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>center a div and add background color</title>
<style type="text/css">
.wrapper{
width: 100%;
height: 400px;
background-color: blue;
margin: 0 auoto;
}
.centered-element{
width: 50%;
height: 200px;
margin: 0 auto;
background-color: red;
}
p{
text-align: center;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="centered-element">
<p>this div is centered!</p>
</div>
</div>
</body>
</html>
我所做的是給了div,我想中心對齊0自動邊緣;這將中心對齊div。我希望這有助於!
你對「頁面中心」有什麼意義?首先嚐試使用'background-color'而不是'background'。 – rendon 2014-09-20 16:56:28
將寬度添加到您的div並做邊距:0 auto; – justrohu 2014-09-20 16:58:42