[英]How to make child content vertically in center as respect to parent container in bootstrap 4
我一直在嘗試根據父容器使我的孩子內容垂直居中。 但是子容器始終相對於父容器。 以下是我嘗試過的代碼:
的HTML
<section id="welcome" class="bg-primary d-flex flex-column">
<h1>Positions</h1>
<div class="container text-center my-auto">
Centered content
</div>
</section>
的CSS
#welcome{
min-height:150px;
width: 200px;
}
我正在尋找的是使“ 居中內容”文本按照整個部分垂直居中。
這是codepen鏈接: CodePen
只需將h1
position-absolute
設為position-absolute
即可將其從DOM中的相對位置中刪除...
https://codepen.io/anon/pen/EeVXbe
<section id="welcome" class="bg-primary d-flex flex-column">
<h1 class="position-absolute">Positions</h1>
<div class="container text-center my-auto">
Centered content
</div>
</section>
您的h1元素是導致其未對齊的原因。 如果您擺脫它(只是為了測試),您會看到居中的內容移到了中心。
顯示:flex; 適用於所有直接子元素,因此您要對齊h1和#welcome元素的總高度。 要將居中的內容放置在一個大正方形的中心,可以將#welcome上的某些樣式應用於.my-auto:
.my-auto {
min-height: 150px;
display: flex;
align-items: center;
justify-content: center;
background: blue;
}
align-items是使用display:flex時的垂直對齊方式。 但是,如果使用flex-direction:列,則方向是“旋轉的”,因此您將使用justify-content:center,通常用於水平對齊。
另一種方法是在要居中的內容的頂部和底部使用填充:
.my-auto {
padding: 50px 0; /* 50px is an arbitrary number, just to demonstrate */
}
請注意,這將導致居中的內容將所有其他元素垂直推離它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.