Search code examples
htmlcssbootstrap-4centertext-align

How can I center some text using bootstrap 4 in a full sized jumbotron and setting a max-width for just the div or p container?


I'm learning how to use bootstrap 4 and when I try to horizontal center some text in a full sized jumbotron, it works just fine. When I try to put a max-width on that text container, it then puts all of the text onto the left hand side of the jumbotron.

Using the class="d-flex justify-content-center align-items-center" makes it work. Once I add the style="max-width: 600px" it breaks it and puts the text to the far left.

Here is my current code:

<div class="jumbotron">
    <h1 class="display-4 text-sm-center">Main Header</h1>
    <div style="max-width: 600px" class="d-flex justify-content-center align-items-center">
        <p class="lead">Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Duis mollis, est non commodo luctus. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Duis mollis, est non commodo luctus.</p>
    </div>
</div>

I would like the text to have a max-width of 600px and be horizontally centered in the jumbotron.


Solution

  • Adding the CSS margin: auto; should do the trick for you. I added a snippet.

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    
    <div class="jumbotron">
    
        <h1 class="display-4 text-sm-center">Main Header</h1>
        
        <div style="max-width: 600px; margin: auto;" class="d-flex center justify-content-center align-items-center">
        
            <p class="lead">Vivamus sagittis lacus vel augue laoreet rutrum 
                faucibus dolor auctor. Duis mollis, est non commodo luctus. 
                Vivamus sagittis lacus vel augue laoreet rutrum faucibus 
                dolor auctor. Duis mollis, est non commodo luctus.</p>
            
        </div>
        
    </div>

    You should avoid inlining CSS, consider putting the CSS in a separate file and importing it.