html - CSS 居中 DIV 包含其他 DIV

标签 html css frontend

如何使用 CSS 将一个 div 水平居中放置在一个 div 中?我正在尝试,我让它从左和右居中,但我无法让它从顶部和底部居中。

        html {
        height:100%;
    }
    body {
        padding:0px;
        margin: 0px;
        height:100%;
    }
    #openFrame {
        position:fixed;
        top:0px;
        width:100%;
        left:0%;
        height:100%;
    }
    .main {
        position: absolute;
        width: 80%;
        max-height: 100%;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }
    #vid {
        width:100%;
        max-height:100%;
        vertical-align: middle;
    }
    #bottom {
        width:100%;
        height:69px;
        background-color: green;
        background-repeat: no-repeat;
        background-position: top center;
        background-size: contain;
    }

最佳答案

将 DIV 垂直居中有点棘手。基本上,您必须将容器的 position 设置为 absolute 并将容器的 position 设置为 relative。然后将 topleft 值设置为 50%,并通过应用负边距减去要居中的元素的宽度/高度的一半。

Codepen example

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <style type="text/css">
        body, html, #container {
            height: 100%;
            width: 100%;
        }
        #container {
            position: relative;
        }
        #content {
            width: 300px;
            height: 300px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -150px;
            margin-left: -150px;
            background-color: red;
        }
        </style>
    </head>
    <body>
        <div id="container">
            <div id="content"></div>
        </div>
    </body>
</html>

关于html - CSS 居中 DIV 包含其他 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30990050/

相关文章:

CSS - 仅调整背景图像的大小,而不是渐变

html - 我怎样才能让这个导航栏更细,背景颜色透明

c# - 执行时自动插入ID

html - 使用内联时所有浏览器中的楼梯影响问题

html - 是否有用于 flex 的 textArea,它支持带有 css 格式的 html 文本?

html - 在动态 div 中垂直对齐图像

javascript - react 动态添加动画反转类

javascript - 如何使 svg 在 div 容器中居中

jquery - 从第三方将 Css 注入(inject) iframe

html - CSS网格列不跨越多列