我想将元素的中心(无论其高度)放在其父元素的底部.我以为我会选择绝对但没有任何意义.见下图:
<div id="red">
<div id="blue"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我怎么能得到这个结果?
编辑:感谢@Gaby aka G. Petrioli我找到了我的解决方案:
#red{
width: 300px;
height: 200px;
background: red;
position:relative;
}
#blue{
width: 100px;
height: 50px;
background: blue;
right:3%;
/* here is the magic solution*/
position:absolute;
bottom: 0;
transform: translateY(50%);
}Run Code Online (Sandbox Code Playgroud)
<div id="red">
<div id="blue"></div>
</div>Run Code Online (Sandbox Code Playgroud)
Gab*_*oli 18
您应该使用绝对位置将其放置在底部,然后使用变换平移将其向上移动50%,因为它的工作与其自身的高度有关.
所以
.red{position:relative}
.blue{
position:absolute;
top:100%;
right:50px;
transform:translateY(-50%);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用CSS 定位,例如:
.red {
position: relative;
}
.blue {
position: absolute;
top: 100%; // Will be at exact bottom
left: 50%;
transform: translate(-50%, -50%); // Will pull 50% (of blue) upwards & 50% from the right as well
}
Run Code Online (Sandbox Code Playgroud)
.red {
position: relative;
}
.blue {
position: absolute;
top: 100%; // Will be at exact bottom
left: 50%;
transform: translate(-50%, -50%); // Will pull 50% (of blue) upwards & 50% from the right as well
}
Run Code Online (Sandbox Code Playgroud)
.red {
background: red;
width: 200px;
height: 300px;
position: relative;
}
.blue {
background: blue;
width: 100px;
height: 200px;
position: absolute;
top: 100%;
left: 50%;
transform: translate(-50%, -50%);
}Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!