我正在学习HTML& CSS所以我试图模仿Coder Manual。
我为背景制作了一个div(我现在只使用一种颜色),另一个div用于第一个带有徽标,导航等的蓝色部分的内容。
但是,我无法使用以下内容使内容div覆盖背景div:
#content {
position: absolute;
top: 0;
}
但这阻止我使用以下内容对内容div进行居中:
#content {
width: 50%;
margin: 0 auto;
}
在这种情况下我该怎么做?
编辑:这里是html:
<!DOCTYPE html>
<html>
<head>
<title>CM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="content">
<img alt="Coder Manual" src="https://codermanual.com/wp-content/uploads/2015/01/logo.png">
</div>
<div id="blue-div">
</div>
</body>
</html>
&#13;
答案 0 :(得分:2)
您可以使用transform
将其置于中心位置:
1 - 在已知position: absolute
width
.center{
height: 40px;
padding: 20px 0;
background: #ddd;
position: relative;
}
.center img{
position: absolute;
left: 50%;
margin-left: -20px; /*the half width */
}
&#13;
<div class="center">
<img src="http://i.stack.imgur.com/gijdH.jpg?s=328&g=1" width="40px" height="40px" alt="LOGO">
</div>
&#13;
2-在position: absolute
width
.center{
height: 40px;
padding: 20px 0;
background: #ddd;
position: relative;
}
.center img{
position: absolute;
left: 50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
}
&#13;
<div class="center">
<img src="http://i.stack.imgur.com/gijdH.jpg?s=328&g=1" width="40px" height="40px" alt="LOGO">
</div>
&#13;
3-垂直居中
.center{
height: 80px;
background: #ddd;
position: relative;
}
.center img{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
&#13;
<div class="center">
<img src="http://i.stack.imgur.com/gijdH.jpg?s=328&g=1" width="40px" height="40px" alt="LOGO">
</div>
&#13;
答案 1 :(得分:1)
就个人而言,我这样做:
.bg {
width: 100%;
}
.bg-blue {
background-color: blue;
}
.content {
text-align: center;
}
&#13;
<div class="bg bg-blue">
<div class="content">
<img alt="Coder Manual" src="https://codermanual.com/wp-content/uploads/2015/01/logo.png">
</div>
</div>
&#13;
但如果您需要保持div
分开:
#BgBlue {
position: absolute;
top: 0;
z-index: -1;
height: 50px;
width: 100%;
background-color: blue;
}
.content {
text-align: center;
}
&#13;
<div id="BgBlue">
</div>
<div class="content">
<img alt="Coder Manual" src="https://codermanual.com/wp-content/uploads/2015/01/logo.png">
</div>
&#13;