将 div 在背景 div 中居中,宽度为 100%,高度为 100%

Centering a div inside a background div with 100% width and 100% height

我遇到了一些奇怪的麻烦。我的问题应该是一个简单的解决方法,但在查看了无穷无尽的 "centering divs" 篇文章后,none 的解决方案有效,我不确定该怎么做!我创建了一个 JS Fiddle 来显示我的问题。

我需要小红框 (#sphere-content) 在我的灰框 (#background) 内水平和垂直居中。通常这可以通过简单地将边距设置为 "auto 0;" 来解决,但由于某种原因,这似乎并不想工作。我不确定这是否与父 div 100% 宽度和高度有关?

相关代码如下:

    <div id="background">
    <div id="sphere-content"></div>
    </div>

    #background {
    margin: 0px;
    padding: 0px;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: -1;
    background-color: #d5d5d5;
    }

    #sphere-content {
    background-color: red;
    width: 50px;
    height: 50px;
    margin: 0 auto;
    }

JS Fiddle: https://jsfiddle.net/e9pL4xg3/11/

在此先感谢您!

您可以将 margin: auto 添加到 #sphere-content,并将 display: flex 添加到 #background html 元素。

JSFiddle