Mis*_*hko 6 html css css-position
我怎么能把蓝色盒子放在红色盒子里?我看到蓝色框的左侧正好位于红色框的中间,但我想将整个蓝色框放在中心,而不是左侧.盒子的尺寸不是恒定的.无论盒子尺寸如何,我都想对齐.在这里玩的例子.谢谢 !
HTML:
<div id="rel">
<span id="abs">Why I'm not centered ?</span>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#rel {
position: relative;
top: 10px;
left: 20px;
width: 400px;
height: 300px;
border: 1px solid red;
text-align: center;
}
#abs {
position: absolute;
bottom: 15px;
width: 300px;
height: 200px;
border: 1px solid blue;
}
Run Code Online (Sandbox Code Playgroud)

小智 2
如果您能够将<span>标签更改为<div>
<div id="rel">
<div id="abs">Why I'm not centered ?</div>
</div>
Run Code Online (Sandbox Code Playgroud)
那么这段 CSS 应该可以工作了。
#rel {
position: absolute;
top: 10px;
left: 20px;
width: 400px;
height: 300px;
border: 1px solid red;
text-align: center; }
#abs {
width: 300px;
height: 200px;
border: 1px solid blue;
margin: auto;
margin-top: 50px; }
Run Code Online (Sandbox Code Playgroud)
我认为最好对封闭的盒子使用更多的自动化,因为如果您更改容器盒子的大小,则需要较少的更改。