两个固定div之间的中心div

时间:2017-05-31 22:52:25

标签: html css

我有两个固定在左边和右边的div。

HTML:

<div class="SideNav1">
    Side Menu1
</div>
<div class="SideNav2">
    Side Menu2
</div>
<div id="Middlediv ">
    Middle Div
</div>

CSS:

.SideNav1 {
    height: 100%; /* 100% Full-height */
    width: 250px; /* 0 width - change this with JavaScript */
    position: fixed; /* Stay in place */
    z-index: 1; /* Stay on top */
    top: 0;
    left: 0;
    background-color: #111; /* Black*/
    overflow-x: hidden; /* Disable horizontal scroll */
}

.SideNav2 {
        height: 100%; /* 100% Full-height */
        width: 250px; /* 0 width - change this with JavaScript */
        position: fixed; /* Stay in place */
        z-index: 1; /* Stay on top */
        top: 0;
        right: 0;
        background-color: #111; /* Black*/
        overflow-x: hidden; /* Disable horizontal scroll */
    }

现在我的目标是在这两个div的中心设置第三个div。我无法让它发挥作用。我试过这样的事情,但没有成功:

#Middlediv {
    background-color: white;
    width: 50px;
    margin-left: auto;
    margin-right: auto;
}

2 个答案:

答案 0 :(得分:4)

使用现有布局,我会使用position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);将中间元素居中。还清理了你的CSS。

&#13;
&#13;
.SideNav1,
.SideNav2 {
  height: 100%;
  width: 250px;
  position: fixed;
  z-index: 1;
  top: 0;
  background-color: #111;
  overflow-x: hidden;
}

.SideNav1 {
  left: 0;
}

.SideNav2 {
  right: 0;
}

#Middlediv {
  background-color: white;
  width: 50px;
  position: absolute;
  left: 50%; top: 50%;
  transform: translate(-50%,-50%);
}
&#13;
<div class="SideNav1">
    Side Menu1
</div>
<div class="SideNav2">
    Side Menu2
</div>
<div id="Middlediv">
    Middle Div
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个https://codepen.io/anon/pen/RVXEVW

搞砸了你的事情之一是div“middlediv”&gt;中的空格。我还在Middlediv的侧面添加了自动宽度和填充。

<强> HTML

<div class="SideNav1">
    Side Menu1
</div>
<div class="SideNav2">
    Side Menu2
</div>
<div id="Middlediv">
    Middle Div
</div>

<强> CSS

body {
    margin: 0;
    padding: 0;
}

.SideNav1 {
    height: 100%; /* 100% Full-height */
    width: 250px; /* 0 width - change this with JavaScript */
    position: fixed; /* Stay in place */
    z-index: 1; /* Stay on top */
    top: 0;
    left: 0;
    background-color: #111; /* Black*/
    overflow-x: hidden; /* Disable horizontal scroll */
}

.SideNav2 {
    height: 100%; /* 100% Full-height */
    width: 250px; /* 0 width - change this with JavaScript */
    position: fixed; /* Stay in place */
    z-index: 1; /* Stay on top */
    top: 0;
    right: 0;
    background-color: #111; /* Black*/
    overflow-x: hidden; /* Disable horizontal scroll */
}

#Middlediv {
    background-color: white;
    width: auto;
    height: 100%;
    margin-top: 0;
    margin-left: auto;
    padding-left: 250px;
    padding-right: 250px;
}