如何在另一个div中定位div [英] how to position divs within another div

查看:130
本文介绍了如何在另一个div中定位div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将div放置在另一个div中。



以下是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); / *不支持
的浏览器的后退rgba * /
background:rgba(0,150,0,.5);
}

和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>

问题是foo / bar / baz / quux块相对于浏览器窗口,

解决问题。



方案

位置:相对添加到父级 .textblock-container div。



绝对定位的元素相对于最接近的父定位(例如,位置为绝对 relative ),所以如果他们没有显式定位的父对象(默认位置是 static ),它们将相对于窗口。 / p>

I want to position divs within another div.

Here's the relevant snippet of css (full example on 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:

    <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.

What am I doing wrong and how can I fix it?

解决方案

Add position: relative to the parent .textblock-container div.

Absolutely positioned elements are positioned relative to their nearest positioned parent (e.g. the nearest parent element with a position of absolute or relative), so if they have no explicitly positioned parents (default position is static) they will be relative to the window.

这篇关于如何在另一个div中定位div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆