Html 如何在另一个 div 中定位 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/17620355/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to position divs within another div
提问by Jason S
I want to position divs within another div.
我想在另一个 div 中定位 div。
Here's the relevant snippet of css (full example on cssdesk):
这是 css 的相关片段(cssdesk 上的完整示例):
        .textblock-container {
            width: 500px;
            height: 500px;
            border: 1px solid red;
        }
        div.textblock {
            width: 100px;
            height: 100px;
            line-height: 100px;
            border: 1px solid black;
            position: absolute;
            text-align: center;             
            background: rgb(0, 150, 0); /* Fall-back for browsers that don't
                                support rgba */
            background: rgba(0, 150, 0, .5);
        }
and the relevant snippet of html:
以及相关的html片段:
    <div id='blockdiv1' class='textblock-container'>
        <div id='blockdiv2' class='textblock'><span>foo (NW)</span></div>
        <div id='blockdiv3' class='textblock'><span>bar (NE)</span></div>
        <div id='blockdiv4' class='textblock'><span>baz (SW)</span></div>
        <div id='blockdiv5' class='textblock'><span>quux (SE)</span></div>
    </div>
The problem is that the foo/bar/baz/quux blocks are positioned relative to the browser window, not to their parent element.
问题是 foo/bar/baz/quux 块是相对于浏览器窗口定位的,而不是它们的父元素。
What am I doing wrong and how can I fix it?
我做错了什么,我该如何解决?
回答by Ennui
Add position: relativeto the parent .textblock-containerdiv.
添加position: relative到父.textblock-containerdiv。
Absolutely positioned elements are positioned relative to their nearest positioned parent (e.g. the nearest parent element with a position of absoluteor relative), so if they have no explicitly positioned parents (default position is static) they will be relative to the window.
绝对定位的元素相对于它们最近的定位父元素(例如,位置为absolute或的最近父元素)进行定位relative,因此如果它们没有明确定位的父元素(默认位置是static),它们将相对于窗口。
回答by Jason S
Unless you add position: relative;to the parent controller the div will be positioned absolute of the window
除非您添加position: relative;到父控制器,否则div 将位于窗口的绝对位置
回答by Lucas Willems
Try this :
尝试这个 :
.textblock-container {
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
}
div.textblock {
width: 100px;
height: 100px;
line-height: 100px;
border: 1px solid black;
position: absolute;
text-align: center;             
background: rgb(0, 150, 0);
background: rgba(0, 150, 0, .5);
}
In fact, you just have to add the position: relativepropertie for the parent div.
实际上,您只需要position: relative为父 div添加属性即可。

