4

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>
Christopher Dias
  • 143
  • 3
  • 10

3 Answers3

8

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>
Rajendran Nadar
  • 4,962
  • 3
  • 30
  • 51
1
<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

1

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>
Luca Spezzano
  • 371
  • 2
  • 14
  • 1
    Whilst code only answers may solve the problem, some explanation of your answer would help others understand what you have done and why you have done it. – Nigel Ren Nov 26 '17 at 19:15
  • This imo is the best answer - just uses classes instead of custom css. – datu-puti Nov 30 '21 at 22:55