将div放在屏幕中心的固定内部

Ric*_*Joe 2 css

我的屏幕顶部有一个div.在这个div里面,我把一个绝对位置,我想要在屏幕中间居中.

#menu{
  position:fixed;
  width:100%;
  height:30px;
  background:#000;
}

#center{
position:absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background:#fff;
}
Run Code Online (Sandbox Code Playgroud)

..

<div id="menu">

<div id="center">
how to center this div?
</div>

</div>
Run Code Online (Sandbox Code Playgroud)

如果我将#menu位置更改为相对它可以正常工作......但我需要修复它.我不能把div #center放在中间的问题是什么?

https://jsfiddle.net/y5s77mmq/1/

谢谢啦!

Dre*_*edy 9

有两种方法可以实现这一目标.一个是给你的#centerdiv一个fixed位置:

#center {
    position:fixed; /* change this to fixed */
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background:#fff;
}
Run Code Online (Sandbox Code Playgroud)

但是,这将使其保持在屏幕中心而不是页面.

如果要在网页上垂直和水平居中,可以使用flex以下选项:

#container {
  display: flex;
  /* establish flex container */
  flex-direction: column;
  /* make main-axis vertical */
  justify-content: center;
  /* align items vertically, in this case */
  align-items: center;
  /* align items horizontally, in this case */
  height: 500px;
  /* for demo purposes */
  border: 1px solid black;
  /* for demo purposes */
  background-color: #eee;
  /* for demo purposes */
}

.box {
  width: 300px;
  margin: 5px;
  text-align: center;
}

#center {
  background: #fff;
  width:100px;
  height:100px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <!-- flex container -->

  <div id="center" class="box">
    how to center this div?
  </div>

</div>
Run Code Online (Sandbox Code Playgroud)

此外,由于#centerdiv与div无关#menu,因此不应嵌套.