如何在不使用定位属性的情况下保持子元素垂直和水平居中

how to keep child element centered vertically and horizontally without using positioning properties

我有三个 div 如下所示。我想将内部 div 保持在外部 div 的正中心。我找到了一些带有位置样式集的解决方案,但它给我项目中的其他元素带来了问题,所以我不想在样式中使用位置。我想在不使用位置样式的情况下居中 div。

<div id="container">
    <div id="outer">
        <div id="inner"></div>
    </div>
</div>

您可以使用 CSS flexbox.

#outer {
    display: flex; /* establish flex container */
    justify-content: center; /* center #inner horizontally */
    align-items: center; /* center #inner vertically */
}

请注意,所有主要浏览器都支持 flexbox,except IE 8 & 9. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add all the prefixes you need, post your CSS in the left panel here: Autoprefixer

DEMO

找到另一个解决方案

#outer {
    display: table-cell;
    vertical-align: middle;
}
#inner {
    margin:auto;
}

http://jsfiddle.net/dspLofov/1/

这是我将 div 置于 div 中心的方法,css 如下所示

#outer {

    background: green;
    height: 200px;
    width: 200px;
    position: relative;
}

#inner {
    position: absolute;
    top: 50%;
    bottom: 50%;
    left: 50%;
    width: 50%;
    height: 50%;
    overflow: auto;
    background: red;
    transform: translate(-50%, -50%);
    resize: both;
    padding: 1em;
}
//I put color in the background so it is easy to see.

这里是 fiddle:https://jsfiddle.net/dwillhite/464Lf6wr/embedded/result/

希望对您有所帮助!