Tips for aligning objects within a bootstrap column so that they all have the same starting point on the X axis

To recreate the issue I am facing, I created a basic HTML structure with 2 bootstrap columns. My aim is to have multiple <p> elements in the second column, stacked one below the other. However, the problem arises when these <p> tags contain text of varying lengths. I want them to appear centered within the column while also starting at the same position along the X-axis.

<body>
<h2 class="text-center my-5">
    title
</h2>
<div class="container">
    <div class="row">
        <div class="col-md-6 ">
            Some unrelated text
        </div>

        <div class="col-md-6">
            <p>Small text</p>

            <p>A much longer text</p>

        </div>

    </div>

</div>

I specifically want the "A much longer text" string to be positioned directly below "Small text," creating this desired layout:

Small text
A much longer text

Instead of:

   Small text
A much longer text

I attempted using text-align:center and flexbox with align-items:center on the column but encountered the same outcome in both cases.

Answer №1

To start, you should include the d-flex justify-content-center classes in your column and then insert a parent div around your p tag. Your code will look like this:

<div class="container">
    <div class="row">
        <div class="col-md-6 ">
            Some random text
        </div>

        <div class="col-md-6 d-flex justify-content-center">
            <div>
            <p>Small piece of text</p>

            <p>An even longer piece of text</p>
            </div>


        </div>

    </div>
</div>

Answer №2

If you are facing issues with bootstrap 4 responsiveness, using the flex box should help resolve the problem. When you test the code provided below, you will notice that the col-md-6 is being split into 2 lines due to bootstrap's responsive behavior. To see the desired outcome, try running the code outside of stack overflow.

Note: I have included some JavaScript code based on feedback from the OP to center the text.

$( document ).ready(function() {
    let divLeft = $('#div-center-text').position().left;
    
    let min = 0;
    $('.center-text').each(function(i, obj) {
      let p = $(obj);
      let pLeft = p.position().left;
      if (min==0 || min>pLeft)
        min = pLeft;
    });
    
    $('.center-text').each(function(i, obj) {
      $(obj).offset({left: divLeft + min});
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
    <html>

      <head>
        <title></title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
      </head>

      <body>
        <h2 class="text-center my-5">
          title
        </h2>
        <div class="container">
          <div class="row">
            <div class="col-md-6 border">
              Some unrelated text
            </div>
            <!-- .col-md-6 -->
            <div class="col-md-6 border" id="div-center-text">
              <div class="d-flex flex-column align-items-center w-100">
                <p class="mb-0 center-text">Small text</p>
                <p class="mb-0 center-text">A much longer text</p>
              </div>
              <!-- .flex-column -->
            </div>
            <!-- .col-md-6 -->
          </div>
          <!-- .row -->
        </div>
        <!-- .container -->
      </body>
    </html>

https://i.sstatic.net/eQsMi.png

Answer №3

To solve the alignment issue and center the content horizontally on a page using Bootstrap, follow the example below:

<div class="pricing4 bg-light" style="margin-top: -20px;padding-bottom: 25px;margin-bottom: -32px;">
<div class="container">
    <h2 style="text-align: center;padding: 40px;">This is improper content (div)</h2>
    <div class="row justify-content-md-center">
        <div class="row justify-content-md-center" style="margin-left: 30px;margin-right: 30px;">
            <div class="col-md-3">
                <div class="card card-shadow border-0 mb-4">
                    <img class="card-img-top" src="https://i.ibb.co/GFrTmrm/dummy-size.jpg" alt="wrappixel kit">
                    <div class="pveventcard">Tuesday 11th May, 6:00PM</div>
                    <div class="p-3" style="height: 200px;">
                        <h6 class="font-weight-medium mb-0">The event is going bla</h6>
                        <h6 class="subtitle font-13">16/5/2021</h6>
                        <p>short description goes here short</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-shadow border-0 mb-4">
                    <img class="card-img-top" src="https://i.ibb.co/GFrTmrm/dummy-size.jpg" alt="wrappixel kit">
                    <div class="pveventcard">Tuesday 11th May, 6:00PM</div>
                    <div class="p-3" style="height: 200px;">
                        <h6 class="font-weight-medium mb-0">The event is going bla</h6>
                        <h6 class="subtitle font-13">16/5/2021</h6>
                        <p>short description goes here short</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-shadow border-0 mb-4">
                    <div class="embed-responsive embed-responsive-16by9">
              <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/YE7VzlLtp-4"></iframe>
          </div>
                    <div class="pveventcard">Tuesday 11th May, 6:00PM</div>
                    <div class="p-3" style="height: 200px;">
                        <h6 class="font-weight-medium mb-0">The event is going bla</h6>
                        <h6 class="subtitle font-13">16/5/2021</h6>
                        <p>short description goes here short</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue when passing a response using coverage.js

I am utilizing coverage.js to showcase data. When I pass my variable containing the coverage response into an HTML file, similar to how it's done in Angular to display expressions, I encounter a syntax error: <div class="container" style="margin- ...

What are some ways I can customize this jQuery :submit selector demonstration?

After reviewing the jQuery example provided here, I am curious about how to adjust the code in order to change the color of a cell only when the value of the submit button within that cell meets certain criteria. For instance: var submitEl = $( ...

Prevent pinch zoom in webkit (or electron)

Is there a way to prevent pinch zoom in an electron app? I've tried different methods, such as using event.preventDefault() on touchmove/mousemove events in JavaScript, adding meta viewport tags in HTML, adjusting -webkit-text-size-adjust in CSS, and ...

Leveraging LESS variables within media queries

After inputting the less code below into : @item-width: 120px; @num-cols: 3; @margins: 2 * 20px; @layout-max-width: @num-cols * @item-width + @margins; @media (min-width: @layout-max-width) { .list { width: @layout-max-width; } } The resul ...

Change the background color of the entire grid page to create a unique look

Is there a way to make the background color different for blocks 3 through 6 while maintaining a full-page background color effect without any padding or margin? .container { display: grid; grid-template-columns: 1fr 1fr; column-gap: 1.5%; ...

Trouble assigning the 'data' attribute to the 'Object' tag using jQuery. [Limited to IE8]

I have encountered a problem when creating an object element dynamically in jQuery to display some content. The code functions perfectly in all browsers except for IE8. Here is the code snippet: j$(document).ready(function(){ j$('.ob ...

Is there a way to hide an HTML element from view while still allowing it to be found by the browser?

Scenario: A collection of cards with hidden names, but still necessary to search by name Picture album cards without any album names visible, only the images, yet still searchable using Ctrl+F Is there a particular feature or CSS code that would enabl ...

Choose children input textboxes based on the parent class during the onFocus and onBlur events

How can I dynamically add and remove the "invalid-class" in my iti class div based on focus events in an input textbox, utilizing jQuery? <div class="form-group col-md-6"> <div class="d-flex position-relative"> & ...

CodeIgniter functionality for generating auto-incrementing IDs that are accessible in both the view and within JavaScript's Window.Print() method

While working on creating an invoice, I encountered a few issues. First, I want the Invoice No: to be displayed in my view (receipt.php) as 0001 and use it as the primary key in my tbl_payment table. However, I'm unsure how to have an auto-incremented ...

Switching to a different template for the website results in unrecognized style formats

As someone new to developing in both Django and Bootstrap, I am wondering if it's possible to use both for templates simultaneously. I have an entire HTML site built with Bootstrap that I'd like to use as a base.html file. However, when I attemp ...

Incorporating accordion functionality using jQuery within my Model-View-Controller

Struggling to integrate accordion jquery with my MVC view. I want it to show content when @item["name"] is selected, but currently it's not working. Here is the script I'm using: <script> $(function () { $("#parameter_accordion").acco ...

What is the best way to extract both the link and text from an <a> tag that contains another element in XPath?

In a similar way to my current data (which cannot be shared due to company policy), the example below is based on information extracted from this response and this response. The aim is to extract both the text of the <a> element and the link itself. ...

What is causing the dysfunction of angular2 form when used with the HTML <form> tag?

Can someone explain the strange behavior of the <form> element in ng2 to me? I have noticed something odd and need some clarification :) To demonstrate, I have created a simple Plunker example at this link: https://plnkr.co/edit/vdrHJBNdd26y6YhPXTHD ...

Is it possible to store an HTML element tag in a variable?

I've been learning JavaScript on w3schools and freecodecamp, but I stumbled upon something in w3schools that has me puzzled. Can someone please explain why this particular code snippet works? The variable "text" is declared as containing the string " ...

JavaScript-enhanced HTML form validation

I encountered a small glitch while working on simple form validation with JavaScript. I tried to catch the issue but have been unable to do so. Here is the code snippet, where the problem lies in the fact that the select list does not get validated and I ...

CSS: The element's relative size causes the background image to vanish

I am facing an issue with displaying a background-image that is 800x480 pixels. The background image appears when the element has a fixed size, but not when the element has a relative size or a max-width. Functional CSS code: .audio-container, .settings- ...

Is it feasible to place an image on top of a box?

Hello everyone, I have been trying to figure out how to achieve a specific layout in React. I am using MUI so there is no need for any hard-coded CSS. However, my attempts have not been successful so far. The layout I am aiming for consists of an image on ...

Polyfill for the :nth-column CSS4 Grid-Structural pseudo-class

In my CSS grid layout, I want to include a margin in every even column. While the :nth-column pseudo-class would be ideal for this, it unfortunately won't be supported in the near future. Could anyone recommend any polyfills that I could utilize, or ...

Fetching Information From Database Using PHP

I am encountering an issue while attempting to transfer data from my HTML table to my modal (without using bootstrap). In the image below, you can see that I have successfully displayed data from MySQL database in the table. The problem arises when I clic ...

"I'm experiencing an issue where my JSON data is not displaying in the browser when I run the code

I am having trouble displaying my json data in the browser. This is my first time working with json and I can't seem to identify the issue. I tried researching online and found that it could be related to mime types, but I still can't solve it. B ...