Equal Height Blocks in Bootstrap with JavaScript

CK CK 3788 
Created at  
709 0 0

In web design, aligning elements of varying heights can be a challenge, especially when you want them to maintain a uniform appearance. One common scenario is aligning blocks with different content heights in a row. Fortunately, with Bootstrap and a bit of JavaScript, you can easily achieve this.

The Problem

Let's say you have three blocks of content side by side, but each block has a different height:\

<div class="row">
    <div class="col-md-4">
        <div class="block" style="height: 150px;">Block 1</div>
    </div>
    <div class="col-md-4">
        <div class="block" style="height: 200px;">Block 2</div>
    </div>
    <div class="col-md-4">
        <div class="block" style="height: 180px;">Block 3</div>
    </div>
</div>

 

The Solution

We can use JavaScript to dynamically adjust the height of each block based on the tallest block's height. Here's how you can do it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Equal Height Blocks</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        /* Optional: Adjust some styles for better presentation */
        .block {
            background-color: lightblue;
            border: 1px solid blue;
            margin-bottom: 10px;
            padding: 10px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row" id="blocksContainer">
        <div class="col-md-4">
            <div class="block" style="height: 150px;">Block 1</div>
        </div>
        <div class="col-md-4">
            <div class="block" style="height: 200px;">Block 2</div>
        </div>
        <div class="col-md-4">
            <div class="block" style="height: 180px;">Block 3</div>
        </div>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
    $(document).ready(function(){
        // Function to adjust the height of blocks
        function adjustBlockHeight() {
            var maxHeight = 0;
            // Loop through each block to find the maximum height
            $('.block').each(function(){
                var blockHeight = $(this).height();
                if (blockHeight > maxHeight) {
                    maxHeight = blockHeight;
                }
            });
            // Set the maximum height to all blocks
            $('.block').height(maxHeight);
        }

        // Call the function initially and whenever the window is resized
        adjustBlockHeight();
        $(window).resize(adjustBlockHeight);
    });
</script>

</body>
</html>

 

How It Works

  1. We start by defining our blocks with different heights.
  2. JavaScript function adjustBlockHeight() calculates the maximum height among all blocks.
  3. This maximum height is then applied to all blocks, ensuring they have the same height.

With this approach, no matter how much the content inside each block varies, they will always align perfectly.

Conclusion

Equalizing the height of blocks in Bootstrap with JavaScript is a powerful technique for creating visually appealing layouts. It ensures that your content remains organized and maintains a consistent appearance across different screen sizes. So next time you're facing the challenge of aligning different height elements, remember this simple yet effective solution.

 

 

Tags Bootstrap Frontend Development JavaScript Responsive Design Web Development Facebook X
Comments 0
Similar posts
  1. Mastering Excel Data Importation in PHP
    553
  2. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    590
  3. JavaScript code to load XML Document
    601
  4. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  5. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    735
  6. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  7. CentOS 7 PHP Apache Kafka: Installation, Examples, and System Diagram
    305
  8. Simple Java Code to display Hello, World on the web
    554
  9. Tailwind CSS and shadcn/ui for React App with Charts and Graphs
    1,039
  10. What Replaced JSP? Modern Java Web Dev Explained (with Examples)
    252
  11. To block copy & paste on your blog content
    899
  12. Shake your browser window by Javascript
    933
  13. Photoshop script programming in Javascript
    531
  14. To compare two HTML tables on web page in real time
    514
  15. To hide/show area of web page without re-loading a page
    1,019
  16. Displays the html tags without rendering on a webpage
    350
  17. Javascript based query parser for AJAX application
    564
  18. To get web browser capability
    522
  19. Photo thumbnail viewer implemented in javascript
    482
  20. Javascript Confirmation
    589
  21. Javascript Prompts
    448
  22. How to know browser version in javascript ?
    439
  23. How to know the browser name in Javascript ?
    639
  24. Select All, None, Invert checkbox
    504
  25. Simple RSS Reader based on javascript
    502
  26. How to find the ip address of a client machine from a web application?
    518
  27. Clipboard copy function working
    3,354
  28. IFRAME Auto Resize in IE, FireFox by Javascript
    454
  29. How to include Javascript from anonther ?
    409
  30. Javascript based Browser Sniffing
    430
  1. Code to Extract the Site Thumbnail Image for Twitter or Facebook
    389
  2. JavaScript Code to Get the Page Title
    331
  3. JavaScript Code to Get Meta Description from HTML
    393
  4. Javascript code to extract favicon URL
    395
  5. RSS to Array in JavaScript
    2,138
  6. Javascript function to convert sitemap.xml to array
    595
  7. Understanding Elasticsearch from Installation to Trouble Shooting
    909
  8. IndexNow for better SEO
    316
  9. Enhancing SEO for Single Page Applications: Implementing Dynamic URL Updates
    1,037
  10. Method to ignore JavaScript Errors globally instead of try... catch for each of cases
    968
  11. Method to catch the browser console log and errors for remote web debugging
    2,166
  12. Atlassian Jira Ticket API Response Example
    2,748
  13. Three different type of Word-Wrap options in HTML CSS
    1,181
  14. JavaScript code to load XML Document
    601
  15. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    590
  16. Copy text to clipboard in Javascript
    1,714
  17. To block copy & paste on your blog content
    899
  18. Shake your browser window by Javascript
    933
  19. Photoshop script programming in Javascript
    531
  20. To compare two HTML tables on web page in real time
    514
  21. To hide/show area of web page without re-loading a page
    1,019
  22. Displays the html tags without rendering on a webpage
    350
  23. Javascript based query parser for AJAX application
    564
  24. To get web browser capability
    522
  25. Photo thumbnail viewer implemented in javascript
    482
  26. Javascript Confirmation
    589
  27. Javascript Prompts
    448
  28. How to know browser version in javascript ?
    439
  29. How to know the browser name in Javascript ?
    639
  30. Select All, None, Invert checkbox
    504
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,731
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252