skip to Main Content

Goal: Have text centered on the screen but still aligned to the left using Bootstrap 4. It should work regardless of the length of the item.

                            List Item
                            Longer List Item
                            Longer List Item With Lots of Info
                            Short

Getting the items to be centered was simple but then getting them to align left has been difficult. Any advice?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet"/>
<div class="col text-center">
<p> List Item </p> 
<p> Longer List Item </p> 
<p> Longer List Item With Lots of Info </p> 
<p> Short </p> 
</div>

3

Answers


  1. You need your .col to be also a flex container (d-flex)and wrap the content into a single div, then center it (justify-content-center) . You can use the bootstrap classes for that.

    example below :

    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet" />
    <div class="d-flex col justify-content-center">
      <div>
        <p> List Item </p>
        <p> Longer List Item </p>
        <p> Longer List Item With Lots of Info </p>
        <p> Short </p>
      </div>
    </div>

    or

    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet" />
    <div class="d-flex col ">
      <div class="mx-auto">
        <p> List Item </p>
        <p> Longer List Item </p>
        <p> Longer List Item With Lots of Info </p>
        <p> Short </p>
      </div>
    </div>
    Login or Signup to reply.
  2. Just put a width on the container (it could be fixed pixel or percentage) and apply auto left and right margin.

    <div class="container">
        <div class="row">
            <div class="col-3 mx-auto">
                <p> List Item </p> 
                <p> Longer List Item </p> 
                <p> Longer List Item With Lots of Info </p> 
                <p> Short </p>
            </div>
        </div>  
    </div>
    

    enter image description here

    demo: https://jsfiddle.net/davidliang2008/f5caxky3/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search