[英]How to horizontally center an absolutely positioned div over its relatively positioned parent?
[英]How to horizontally center fixed content within absolutely positioned parent?
我在我的應用程序中顯示一個模態,它固定在占據整個窗口的絕對定位容器中。
像這樣:
<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的核心更改是從與浮動對齊轉變為使用Flexbox,這是有原因的。 實際上,他們圍繞flexbox重新設計了整個Bootstrap網格系統-Bootstrap的核心。
通過將這兩行添加到父div:
display:flex;
justify-content:center;
並從子div中刪除這兩行(模式內容):
xxxleft: 50%;
xxxtransform: translateX(-50%);
模態將自動調整,並始終保持居中。
這是我使用過的最終居中指南: https : //css-tricks.com/centering-css-complete-guide/
這將遍歷所有以問答格式居中的選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.