CSS 如何将另一个div内的div放置到绝对位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15068624/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:46:30  来源:igfitidea点击:

How to place div inside another div to absolute position?

csscss-position

提问by Stybos

For instance, I would like to create a template like in the image below.

例如,我想创建一个如下图所示的模板。

http://i.imgur.com/OneRsMw.png

http://i.imgur.com/OneRsMw.png

How do you position each div inside the container to its absolute position? I would prefer without needing to use float-attributes. Any short examples would be appreciated.

如何将容器内的每个 div 定位到其绝对位置?我宁愿不需要使用浮动属性。任何简短的例子将不胜感激。

回答by Gabriele Petrioli

You can use absoluteand relativepositioning.

您可以使用absoluterelative定位。

for example

例如

html

html

<div id="container" class="box">
    <div class="box top left"></div>
    <div class="box top center"></div>
    <div class="box top right"></div>

    <div class="box middle left"></div>
    <div class="box middle center"></div>
    <div class="box middle right"></div>

    <div class="box bottom left"></div>
    <div class="box bottom center"></div>
    <div class="box bottom right"></div>
</div>

css

css

#container{
    width:200px;
    height:200px;
    position:relative;
    border:1px solid black;
}
.box{
    border:1px solid red;
    position:absolute;
    width:20px;
    height:20px;    
}

.top{top:0}
.middle{top:50%;margin-top:-10px;/*half of the .box height*/}
.bottom{bottom:0}

.left{left:0;}
.center{left:50%;margin-left:-10px;/*half of the .box width*/}
.right{right:0;}

Demo athttp://jsfiddle.net/gaby/MB4Fd/1/

演示在http://jsfiddle.net/gaby/MB4Fd/1/

(ofcourse you can adjust the actual positioning to you preference, by changing the top/left/right/bottom values)

(当然,您可以通过更改顶部/左侧/右侧/底部值来根据自己的喜好调整实际定位

回答by adrift

Use position: relative;on the container (a <div>containing all the content) and absolutely position the child elements. The child elements inside the container will be positioned relative to the container so it would be pretty easy to lay everything out to your needs.

position: relative;在容器上使用(a<div>包含所有内容)并绝对定位子元素。容器内的子元素将相对于容器定位,因此很容易根据您的需要布置所有内容。

However, It's considered bad practice to use positioning in most circumstances to lay your site out .. I'd suggest using floats even though you claim to not want to, you'll have much more consistency across different browsers.

但是,在大多数情况下使用定位来布置您的网站被认为是不好的做法。我建议您使用浮动,即使您声称不想这样做,您将在不同浏览器之间获得更多的一致性。

Read thisarticle if you're confused about floats

如果您对浮动感到困惑,请阅读这篇文章