How do I vertically and horizontally center text in a container in bootstrap 4?

Viewed 7361

Let's say I want to center the h1 and p elements in the division.

<div id="outer" class="container">
 <div id="inner">
  <h1>Heading</h1>
  <p>Some content</p>
 </div>
</div>
3 Answers

It is very easy makes the parent div as display: flex and make the child element margin: auto;

Check the demo below.

#outer {
  width: 100%;
  height: 100vh;
  display: flex;
}

#inner {
  margin: auto;
}
<div id="outer" class="container">
  <div id="inner">
    <h1>Heading</h1>
    <p>Some content</p>
  </div>
</div>

<div id="outer" class="container text-center">
<div id="inner">
<h1>Heading</h1>
<p>Paragraph</p>
</div>
</div>

#outer{
min-height:100vh;
display:flex;
}

#inner{
margin:auto;
}

Please update your code as above. For #outer use display:flex & min-height:100vh which will span 100% of screen. For #inner use margin:auto to centered the text

Bootstrap 4 use flexbox, so d-flex assign the property display: flex than align-items-center aligns it vertically and justify-content-center aligns it horizontally.

<div id="outer" class="container d-flex align-items-center justify-content-center">
    <div id="inner">
      <h1>Heading</h1>
      <p>Some content</p>
    </div>
</div>
Related