<分区>
<分区>
我有一个 div(子),它在父容器中绝对定位(相对定位)。我希望这个子 div 在桌面和移动设备上都在其容器内垂直和水平居中,但是子 div 会根据窗口的大小移动定位。如何跨设备应用一致的居中定位?
HTML
<div class="container">
<div class="child">
</div>
<div class="child-2">
</div>
</div>
CSS
.container {
width: 300px;
height: 300px;
border: solid 1px blue;
position: relative;
}
.child {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
position: absolute;
right: 50%;
left: 50%;
top: 50%;
border-radius: 100%;
}
.child-2 {
border-bottom: solid 1px blue;
width: 300px;
height: 150px;
}
例如 JSFiddle - http://jsfiddle.net/hfndkywe/8/
最佳答案
使用transform使元素居中总是安全的,看下面代码
.child {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
left: 50%;
top: 50%;
border-radius: 100%;
transform: translate(-50%,-50%);
}
当你使用左右定位时,它总是从侧面而不是中心插入 div,所以为了准确地在中心变换是很容易的解决办法。
关于html - 居中位置 : absolute div in relative container in desktop and mobile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51212630/