我在我的应用程序中显示一个模态框,它固定在占据整个窗口的绝对定位容器中。
像这样:
<div>
<div class="modalWrap">
<div class="modalContent">
howdy slick willy
</div>
</div>
</div>
.modalWrap {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
background-color: pink;
}
.modalContent {
width: 150px;
background-color: white;
border: 1px solid black;
padding: 15px;
position: fixed;
top: 50px;
left: 50%;
transform: translateX(-50%);
}
https://jsfiddle.net/513m6kte/3/
当容器被设置为占据整个窗口宽度(right: 0
)时它起作用。但是,我有一个聊天窗口可能从右侧进入的用例,因此我需要容器不要占据整个宽度。这很容易通过将容器上的 right
设置为 250px
来实现,但模态内容将不再居中。
当容器的宽度发生变化时,如何使模态框在 .modalWrap
中保持居中?
最佳答案
有一个更简单的解决方案,使用 flexbox。
Flexbox 相对较新,但非常有用 - 而且非常简单。从 Bootstrap3 到 Bootstrap4 的核心变化是从与 float 对齐转向使用 Flexbox 是有原因的。 事实上,他们围绕 flexbox 重新设计了整个 Bootstrap 网格系统——Bootstrap 的核心。
通过将这两行添加到父 div:
display:flex;
justify-content:center;
并从子 div(模态内容)中删除这两行:
xxxleft: 50%;
xxxtransform: translateX(-50%);
模态框会 self 调整,并始终保持居中。
引用资料:
关于html - 如何在绝对定位的父级中水平居中固定内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56266014/