需要帮助CSS以绝对定位为中心

Gen*_* S. 10 html css css-position

我从未对我在网页中集中内容的各种解决方案感到十分满意.该<center>标签已在18世纪中叶被废弃了回来,但我看不出一个合理的选择.具体来说,我想要的是一个居中的父DIV,但是对于其左上角,我可以"绝对地"设置事物.

有没有办法实现这一点,而不使用window.onresize javascript来重新测量一切?这似乎是一个相当直接的想法...我希望绝对定位的东西,我只是希望0,0坐标相对于浏览器窗口左上角以外的其他东西.

现在,我所做的是设置一个div以使其内容居中,然后以相对位置面对面,但这非常令人厌烦,因为相对的物体不断地以我完全不想要的方式相互推动.

对此的任何和所有想法都非常感激.

Mik*_*son 12

body { text-align: center; }
#wrapper { width: 960px; margin: 0 auto; text-align: left; position: relative; }
#wrapper .child { position: absolute; left: 0; top: 0; }
Run Code Online (Sandbox Code Playgroud)

只是示例代码,但任何.child元素都在包装器的0,0处

任何绝对定位的元素将绝对定位到它最近的位置相对父元素.如果元素没有具有位置相对性的父元素,则它只使用该文档.下面是没有类的示例(为了清晰起见,添加了一些颜色和宽度样式).

<html>
    <body style="text-align: center;">
        <div style="position: relative; width: 100px; height: 100px; margin: 0 auto; background: red;">
            <div style="position: absolute; left: 0; top: 0;">
                This will absolutely position relative to the container div.
            </div>
        </div>
        <div style="position: absolute; left: 0; top: 0; width: 100px; height: 100px; background: blue;">
            This will absolutely position relative to the document
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)


rob*_*rke 8

如果您坚持使用,position: absolute;那么设置您想要定位的div必须position: relative;使其进入任何子元素的定位上下文.

要将绝对定位的div居中,您需要知道它的宽度,然后使用以下CSS:

#wrapper {
    width: 800px;
    margin: 0 auto;
    position: relative; /* creates a positioning context for child elements */
}

#child {
    position: absolute;
    width: 400px;
    left: 50%;
    margin-left: -200px;
}
Run Code Online (Sandbox Code Playgroud)

和HTML:

<div id="wrapper">
    <div id="child">
        ....
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

您可以根据需要调整宽度和左边距(负左边距应该是您居中的div的宽度的一半,例如#child.

正如其他人提到的那样,margin: 0 auto;在设置宽度的元素上使用它会使它居中.


小智 6

这是你想要的 ?

<div style=" position: absolute;
             display: inline-block;
             top: 20%;
             bottom: 20%;
             right: 20%;
             left: 20%;
             background-color: #434154;
             text-align: center;">
    <div style="display: inline-block;
                height: 100%;
                vertical-align: middle;"></div>
    <div style="position: relative;
                color: #FFFFFF;
                background-color: #546354;
                display: inline-block;
                vertical-align: middle;">
               THIS IS CENTERED WITHOUT SCRIPTING :D
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)