What is the best way to horizontally align paragraphs within different divs or spans?

Currently, I have 2 divs placed side by side that each contain about 5 paragraphs. My goal is to align these paragraphs horizontally so that paragraph 2 in the first div starts at the same line as paragraph 2 in the second div (and so on for all other paragraphs). I attempted to use the position function from jQuery UI since I am already using their slider in my project as well (https://jqueryui.com/position/). However, I encountered an issue when one of my paragraphs was too long and did not display properly, causing a misalignment with its corresponding paragraph. Here is the HTML structure I currently have:

<div id="container">
<div id="column-1">
 <p>PARAGRAPH 1</p>
 <p>PARAGRAPH 2</p>
 <p>PARAGRAPH 3</p>
 <p>PARAGRAPH 4</p>
</div>
<div id="column-2">
 <p>PARAGRAPH 1</p>
 <p>PARAGRAPH 2</p>
 <p>PARAGRAPH 3</p>
 <p>PARAGRAPH 4</p>
</div>
</div>

EDIT: Just to clarify, the paragraphs in the divs have varying lengths, which is the main cause of my alignment issue.

Answer №1

Are you looking to achieve the same effect as your HTML code using only CSS/JavaScript, or are you open to making minor changes to the HTML structure?

p {
  display: inline-block;
}
<div class="container">
  <div class="column-1">
    <p>PARAGRAPH 1</p>
    <p>PARAGRAPH 1</p>
  </div>
  <div class="column-2">
    <p>PARAGRAPH 2</p>
    <p>PARAGRAPH 2</p>
  </div>
  <div class="column-3">
    <p>PARAGRAPH 3</p>
    <p>PARAGRAPH 3</p>
  </div>
  <div class="column-4">
    <p>PARAGRAPH 4</p>
    <p>PARAGRAPH 4</p>
  </div>
</div>

Answer №2

If you are looking to achieve the same outcome, consider restructuring your HTML. I have provided a revised version below along with JavaScript examples for accessing paragraphs as needed.

In this layout, if the text in column 1 is longer than that in column 2, column 2 will adjust its size accordingly due to the expansion of the parent row div.

Some CSS styles:

#container {
    margin: 0 auto;
    width: 100%;
}
#container .row {
    /* Targeting rows */
}
#container .row .col {
    float: left;
    width: 50%;
}
/* Styled for #column-1*/
#container .row .col.column-1 {

}
/* Styled for #column-2 */
#container .row .col.column-2 {

}

And here's the corresponding HTML structure:

<div id="container">
    <div class="row">
        <p class="col column-1">PARAGRAPH 1</p>
        <p class="col column-2">PARAGRAPH 1</p>
    </div>
    <div class="row">
        <p class="col column-1">PARAGRAPH 2</p>
        <p class="col column-2">PARAGRAPH 2</p>
    </div>
    <div class="row">
        <p class="col column-1">PARAGRAPH 3</p>
        <p class="col column-2">PARAGRAPH 3</p>
    </div>
    <div class="row">
        <p class="col column-1">PARAGRAPH 4</p>
        <p class="col column-2">PARAGRAPH 4</p>
    </div>
</div>

To target specific columns and paragraphs using JavaScript:

// Selecting #column-1
var col1 = document.querySelectorAll(".column-1");

// Selecting Specific Paragraphs
var col1_par1 = document.querySelector(".row:nth-child(1) .column-1"),
    col1_par2 = document.querySelector(".row:nth-child(2) .column-1");

// Changing Text Color of Paragraph 3 in Column 1 to red
document.querySelector(".row:nth-child(3) .column-1").style.setProperty("color", "red")

Answer №3

Check out my solution in action on Fiddle:

    <div id='holder'>
      <div id='one'>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
      </div>

      <div id='two'>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
        <p>Fooo fooo foooo lorem lorem lorem</p>
      </div>
    </div>

#holder {
  overflow: none;
}

#one{
  display: inline-block;
  background-color: #eee;
  width: 150px;
  height: 300px;
  margin: 5px;
  overflow: hidden;
  overflow-y: scroll;
}

#two{
  display: inline-block;
  background-color: #eee;
  width: 150px;
  height: 300px;
  margin: 5px;
  overflow: hidden;
  overflow-y: scroll;
}

In this setup, I'm utilizing CSS properties like inline block and scroll to hide overflow along the y-axis for each element. It's a simple and effective technique.

See it live on JSFiddle

Answer №4

Exploring the realms of JavaScript led me to a solution that aligns with your requirements, albeit not entirely responsive. Nevertheless, I present this intriguing solution based on DOM and nodes. By retrieving element nodes like p, which are children of column1 and column2, we can compare them. Asking for all the children of column1 would yield p tags and text nodes because a p node contains another node—a text node. The pivotal element here is the height of p elements. Thus, segregating all the children nodes from both columns into separate arrays holding p elements became imperative.

To conclude, my approach involved comparing the p elements in each array within a for-loop. For instance, if the height of paragraph2 in column1 exceeds that in column2, then setting the height of paragraph2 in column2 equal to that of paragraph2 in column1 occurs.

// JS :

var col1 = document.getElementById('column_1');
var col1Children = col1.childNodes;

var col2 = document.getElementById('column_2');
var col2Children = col2.childNodes;

var col1Child_p = [];
var col2Child_p = [];
var col1ChildTextNode = [];
var col2ChildTextNode = [];

col1.classList.add('contentM'); 
col2.classList.add('contentM');

for(var a = 0; a < col1Children.length; a++){
 if(col1Children[a].nodeType === 1){ // if child is an element node (like p)
    col1Child_p.push(col1Children[a]); 
 } else {
    col1ChildTextNode.push(col1Children[a]);
 }
}

for(var b = 0; b < col2Children.length; b++){
 if(col2Children[b].nodeType === 1){
  col2Child_p.push(col2Children[b]);
 } else{
  col1ChildTextNode.push(col2Children[b]); 
 }
}

for (var i = 0; i < 4; i++) {
 var col1ChildHeight = col1Child_p[i].clientHeight;
 var col2ChildHeight = col2Child_p[i].clientHeight;

if (col1Child_p[i].clientHeight > col2Child_p[i].clientHeight) {
   col2Child_p[i].style.height = col1ChildHeight + 'px';
 } else if (col1Child_p[i].clientHeight < col2Child_p[i].clientHeight{
   col1Child_p[i].style.height = col2ChildHeight + 'px';
 } else {
   console.log('not working - already the same height');
 }
}

// CSS :

* {
 box-sizing: border-box;
}

body {
 margin: 0;
 padding: 0;
 font-family: sans-serif;
 font-size: 0.9em;
}

p {
 height: auto;
}

#container {
 width: 80%;
 margin: 0 auto;
}

#column_1 {
 background-color: orange;
}

#column_2 {
 background-color: red;
}

#column_1 p,
#column_2 p {
 background-color: pink;
}

section {
 display: block;
 width: 100%;
 background-color: blue;
}

.contentM {
 width: 47.389558232932%; /* 472 / 996 */
 margin: 0 1.305220883534%; /* 13 / 996 */
 display: inline-block;
 float: left;
}


/* under a screen size of 640 px, a css rule overwrite the javascript calculation : */

@media screen and (max-width: 640px) {
 .container {
  width: auto !important;
  margin: 0 13px;
 }
 .contentL,
 .contentM,
 .contentS {
  width: 100% !important;
  margin: 0 0 13px 0 !important;
 }
 p {
  height: auto !important;
 }
}

@media screen and (max-width: 768px) {
  .container {
   width: 90%;
  }
}

/////////////

Another approach involves utilizing flexbox. This strategy offers cleaner code maintenance and less confusion while being well-supported by modern browsers.

I had to modify the HTML structure to adhere to this method.

// HTML :

<body>
 <div id="container">
  <section>
   <article id="column" class="contentM"> 
    <div>
     <p>PARAGRAPH 1 : Astronomy (from Greek: αστρονομία) is a natural science that studies celestial objects and phenomena</p>
     <p>PARAGRAPH 1 : Astronomy (from Greek: αστρονομία) is a natural science that studies celestial objects and phenomena</p>
    </div>
    <div>
     <p>PARAGRAPH 2 : Astronomy (from Greek: αστρονομία) is a natural science that studies celestial objects and phenomena. It applies mathematics, physics, and chemistry, in an effort to explain the origin of those objects and phenomena and their evolution.</p>
     <p>PARAGRAPH 2 : Astronomy (from Greek: αστρονομία) is a natural science that studies celestial objects and phenomena</p>
    </div>
    <div>
     <p>PARAGRAPH 3 : Astronomy (from Greek: αστρονομία) is a natural science that studies celestial objects and phenomena</p>  
     <p>PARAGRAPH 2 : Astronomy (from Greek: αστρονομία) is a natural science that studies celestial objects and phenomena</p>
    </div>
    <div>
     <p>PARAGRAPH 4 : Astronomy (from Greek: αστρονομία) is a natural science that studies celestial objects and phenomena</p>
     <p>PARAGRAPH 4 : Astronomy (from Greek: αστρονομία) is a natural science that studies celestial objects and phenomena.</p>
    </div>
  </article>
</section>

// CSS :

p {
 width: 100%;
 margin: 5px 5px;
 background-color: orange;
}

container {
 width: 80%;
}

section {
 width: 100%;
}

article {
 margin: 5px 5px;
 background-color: red;
 float: left;
}

.contentM {
 width: 48%;
}

.row {
 display: flex;
}

// JS :

var col = document.getElementById('column');
var rowDiv = document.querySelectorAll('#column > div');

for(var i = 0; i < rowDiv.length; i++){
 rowDiv[i].classList.add('row');
}

////////

In the meantime, @Noot, you mentioned achieving similar results using flex. Did it entail altering the HTML document's structure? Feel free to share your findings.

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

Exploring the functionalities of radio buttons and arrays in a Javascript experiment

Currently delving into the world of Javascript and struggling to wrap my head around creating a test using only pure Javascript (no jQuery). The goal is to: Present users with a question and provide radio button options for selection. Allow users to cho ...

Prevent selection on all elements except for input fields with the type of text

I am facing a challenge where I need to prevent selection on a website page for everything except input[type=text] elements. The answer provided in this accepted response to a similar query almost solves the issue. However, it doesn't stop users from ...

Is there a way to ensure that my footer container maintains the same width as the content when it slides to the left

When I access my testsite at If I click on the top left icon (filter), the content and footer slide to the left, revealing that the footer container does not have the same width as the content container due to the scrollbar in the content. What is the so ...

What could be causing my prompt for a username to not work properly as I attempt to develop a system that generates a unique code using the user's initials?

I'm currently working on a script that will be used by the secretaries in our school district to generate unique codes for new students or hires. The code will consist of an 8-digit output, a randomly generated 6-digit number, and the user's init ...

Fetching locales asynchronously in nuxt.js using i18n and axios: A step-by-step guide

I am facing an issue with getting the location asynchronously. Whenever I try to implement my code, it results in a "Maximum call stack size exceeded" error. How can I resolve this issue? Previously, I attempted to retrieve the location by using the axios ...

Combining shapes in three.js

I've encountered a scenario where my scene consists of multiple meshes, each with different shapes and sizes. By looping through each mesh and utilizing geometry.merge(), I successfully created a new mesh from the geometries in the scene. The challe ...

The <a> tag styled as a button with the btn-primary class is malfunctioning specifically on MacOS Safari

Trying to use an anchor tag with type button and btn-primary class on MacOS safari is causing issues, while it works perfectly on Chrome and Edge browsers <a class="btn btn-primary " style="border-radius: 25px;" type="button&qu ...

Responsive text area with Django and Bootstrap

I created a small JavaScript script to ensure that a text area adjusts responsively based on the size of the accompanying image. It generally works well, but there is a strange random bug that I can't quite figure out. This is how the page should be d ...

Retrieve the highest integer from the server-side for the client

When creating input fields of type number on the client side, I have been setting their max attribute to the maximum integer value in the user's browser using: Number.MAX_SAFE_INTEGER.toString() Now, I need to output an input field on the se ...

Ways to expand the search box in a navigation bar with Bootstrap 5

Recently delving into front-end development, I've been working on designing a webpage that includes a search box (you can view the jsfiddle here). I decided to borrow the navbar component from https://getbootstrap.com/docs/5.0/components/navbar/ and m ...

Implement checkbox functionality for data binding in Vue framework

I'm having trouble figuring out how to display the selected values in Vue. I've got a form that triggers a query based on the user's selections: <form id="Register"> <br>Firstname<input type="checkbox" value="firstNam ...

Tips for emptying form fields when sliding up in jQuery

I have created a user-friendly form for booking hotel accommodations. Users can easily select the number of adults and children from dropdown menus. Additionally, the form dynamically generates dropdowns for specifying the ages of children once selected. ...

What might be preventing me from achieving a full-length page using height 100% or height 100vh?

I am currently working on a web application that has a similar layout to Slack. I am facing an issue where the page doesn't take up the full width and height as intended. The problem seems to be that it sometimes only occupies half of the screen while ...

The inefficacy of the JQUERY validation plugin, AJAX, and PHP integration

After diving into learning AJAX for submitting forms, I've encountered a roadblock. The data I submit doesn't seem to reach the PHP file as expected, and I can't figure out why it's failing. Here's my HTML: <div class="col-md- ...

The conversion of a 2D json array into a string is mistakenly performed

On hand is an outer array that contains 2 arrays within it, making it a 2-dimensional array. This is how the array is initialized: $outerArray = array(); $nestedArray = array("first", "second", "third", "fourth"); $outerArray[] = $nestedArray; $nest ...

What is the best way to calculate the combined total of radio button values using jQuery or JavaScript?

I recently came across a tutorial on how to sum radio button values using JavaScript or jQuery, and I decided to implement it in my code. However, I encountered some issues as it didn't work as expected. My goal was to offer users the option to downlo ...

Having trouble with the error "Cannot GET /" in your Angular2 and Express

I've been working on customizing this GitHub example application to utilize Express instead of KOA. When I enter gulp serve in the CentOS 7 terminal, the app launches successfully. However, upon typing http : // localhost : 8080 in the browser, a 404 ...

Troubleshooting $scope.$on unit testing - event not getting detected

In one of my controllers, I have implemented a simple $scope.$on function: app.controller('MyController', function($scope) { $scope.$on("myBroadRcvr", function(event, data) { $scope.name = data.name; $scope.empID = data.empID ...

Java script request via Ajax is failing to execute

Within my HTML code, I have included a button like so: <button type="submit" id="post-form" class="btn btn-primary" onclick="send()">Send</button> Accompanying this is the JavaScript function send() : fu ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...