I have trouble creating a carousel in Bootstrap 4 with text centered both horizontally and vertically.
I have created the bootply with a carousel, but the text is ju
Simply you are missing this:
<div class="carousel-caption">
Before the <h1>Text 1</h1>
So it's like this:
<div class="carousel-item active">
<div class="carousel-caption">
<h1>Text 1</h1>
</div>
</div>
You can use display: table;
and display: table-cell;
display along with vertical-align: middle;
.carousel-item {
display: table;
text-align: center;
}
.carousel-item h1 {
display: table-cell;
text-align: center;
vertical-align: middle;
}
The key here is vertical-align: middle;
which works only if a div is a table.
Regarding the horizontal alignment, the text-align: center;
goes to .carousel-item
. I updated my code.
Change your CSS for h1
into the following:
.carousel-item h1 {
position: absolute;
margin: 0;
color: white;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
You can use the Bootstrap 4 utility classes (no additional CSS is needed)...
https://www.codeply.com/go/ORkdymGWzM
<div class="carousel slide" data-ride="carousel">
<div class="carousel-inner text-center">
<div class="carousel-item active">
<div class="d-flex h-100 align-items-center justify-content-center">
<h1>Text 1</h1>
</div>
</div>
<div class="carousel-item">
<div class="d-flex h-100 align-items-center justify-content-center">
<h1>Text 2</h1>
</div>
</div>
<div class="carousel-item">
<div class="d-flex h-100 align-items-center justify-content-center">
<h1>Text 3</h1>
</div>
</div>
</div>
</div>