我通常使用相对定位将div放在其父级中心。我发现绝对定位也应该有效。我不确定是什么让我的div不集中。当某个类添加到我的div时,它会从相对位置变为绝对位置,但具有相同类型的边距:
#selectablesDiv{
order: 1;
position: relative;
margin: 10vh auto 30vh auto;
height: 45px;
width: 465.94px;
text-align: center;
user-select: none;
opacity: 1;
display: flex;
flex-direction: row;
&.aboutMeClicked{
position: absolute;
margin: 62vh auto 30vh auto;
}
}
父div已应用以下CSS:
#homePageDiv{
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
position: relative;
overflow: hidden;
animation: backgroundChange 36s ease-in-out 0s infinite;
}
为什么右边距和左边距变为0大小。边缘似乎是基于相对/绝对定位,还是我缺少某些东西?
答案 0 :(得分:2)
您必须使用right : 0;
和left: 0;
将绝对定位元素置于其父级中心(与margin-left: auto;
和margin-right: auto;
结合使用)。
#homePageDiv {
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
position: relative;
overflow: hidden;
animation: backgroundChange 36s ease-in-out 0s infinite;
background-color: red;
}
#selectablesDiv {
order: 1;
position: relative;
margin: 10vh auto 30vh auto;
height: 45px;
width: 465.94px;
text-align: center;
user-select: none;
opacity: 1;
display: flex;
flex-direction: row;
background-color: yellow;
}
#selectablesDiv.aboutMeClicked {
position: absolute;
margin: 62vh auto 30vh auto;
right: 0;
left: 0;
}

<div id="homePageDiv">
<div id="selectablesDiv" class="aboutMeClicked"></div>
</div>
&#13;