如何覆盖两个div,同时将其中一个居中

时间:2015-08-10 17:31:57

标签: html css css3 css-position

我正在学习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">
            &nbsp;     
    </div>
</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以使用transform将其置于中心位置:

1 - 在已知position: absolute

的元素中使用width

&#13;
&#13;
.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;
&#13;
&#13;

2-在position: absolute

未知的元素中使用width

&#13;
&#13;
.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;
&#13;
&#13;

3-垂直居中

&#13;
&#13;
.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;
&#13;
&#13;

答案 1 :(得分:1)

就个人而言,我这样做:

&#13;
&#13;
.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;
&#13;
&#13;

但如果您需要保持div分开:

&#13;
&#13;
#BgBlue {
  position: absolute;
  top: 0;
  z-index: -1;
  height: 50px;
  width: 100%;
  background-color: blue;
}
.content {
  text-align: center;
}
&#13;
<div id="BgBlue">
  &nbsp;
</div>
<div class="content">
  <img alt="Coder Manual" src="https://codermanual.com/wp-content/uploads/2015/01/logo.png">
</div>
&#13;
&#13;
&#13;