Is it possible to ensure that the bottom div in a column matches the width of the top div when both have dynamic widths?

Looking at the code snippet below:

<div id="container">
    <div id="top">
        <img />
    </div>
    <div id="bottom">
        Some text, there we go.
    </div>
</div>

The <img> tag has a fixed height. The width of top and bottom is variable. It's possible that the content in top may be wider than bottom, or vice versa. The goal is to ensure that the width of bottom always matches the width of top.

Is it achievable using only CSS? Or would JavaScript be required?

Answer №1

If you want to achieve this using only CSS, a solution is available courtesy of Artem Polikarpov (in Russian) on his website.

<style>
  .ap-pic {
    display: table-cell;
    width: 1px;
  }

  .ap-pic .caption {
    display: block;
  }
</style>

<div class="ap-pic">
  <img src="pic.jpg">
  <span class="caption">long text that needs to wrap to the next line blah blah blah</span>
</div>

Answer №2

There is no direct correlation between the #top and #bottom elements, except for sharing a common parent. This means that achieving equal width between them could pose some challenges unless one is nested within the other.

An efficient solution using jQuery would be:

$("#bottom").css('width', $("#top").width());

Answer №4

After weeks of struggle and months of fine-tuning, I have finally perfected this solution. Using JQuery, I have implemented a mechanism to ensure that two elements always maintain the same width.

Check out the JSFiddle

/**
 * Fetch basic dimensions of an element
 *  @author PseudoNinja (email at pseudoninja dot com)
 * @returns object
 */

jQuery.fn.getDimensions = function () {
    var $this = $(this),
        dimensions = {
            width: 0,
            paddingLeft: 0,
            paddingRight: 0,
            borderLeft: 0,
            borderRight: 0,
            getOuterWidth: function () {
                return parseInt(this.width) + parseInt(this.paddingLeft) + parseInt(this.paddingRight) + parseInt(this.borderLeft) + parseInt(this.borderRight);
            }
        };

    dimensions.width = $this.width();
    dimensions.paddingLeft = $this.css('padding-left').replace(/[^-\d\.]/g, '');
    dimensions.paddingRight = $this.css('padding-right').replace(/[^-\d\.]/g, '');
    dimensions.borderLeft = $this.css('border-left-width').replace(/[^-\d\.]/g, '');
    dimensions.borderRight = $this.css('border-right-width').replace(/[^-\d\.]/g, '');
    dimensions.outerWidth = $this.outerWidth();

    return dimensions;
};

/** Adjust element width to match target width
 *  @author PseudoNinja (email at pseudoninja dot com)
 *  @param  {string} target - selector of element with desired width
 */
jQuery.fn.sizeTo = function (target) {
    var $this = $(this),
        $target = $(target),
        myDimensions = $this.getDimensions(),
        targetDimensions = $target.getDimensions(),
        difference = targetDimensions.outerWidth - myDimensions.outerWidth,
        adjOuterWidth = 0
    ;

    if (difference > 0) {
        myDimensions.width = myDimensions.width + difference;
        adjOuterWidth = myDimensions.getOuterWidth();
        $this.width(myDimensions.width);
    }

    // Maintain size equality
    setTimeout(function () {
        $this.sizeTo(target);
    }, 100);

    return $this;
};

// EXAMPLE OF USAGE
//    $(function(){
//        $("#div1").sizeTo($("#div2"));
//    });

Answer №5

You can achieve this using only CSS. Simply adjust the width of both elements to 100%.

Answer №6

When approaching it in that manner, I recommend utilizing lists instead of div elements.

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

The CSS Grid does not align properly in the horizontal direction when displayed on mobile devices

I am currently working on a responsive layout where the header and footer should each take up around 5% of the screen space and remain fixed. The middle section should scroll based on the number of elements within it. Despite using the fr and % values, the ...

I am facing an issue where my CSS file is not connecting with my HTML

I added the link to my html pages, but my css is only showing up on the first page and not on any of the others. <head> <title>Angels Drawings</title> <link rel="stylesheet" href="style.css"> <STYLE> <!- ...

Ways to adjust the height of a separate container based on various class attributes

Check out the HTML structure provided below: <div> <div class="custom-bar custom-bar-minimal"></div> </div> <div class="custom-border"> <div class="container"></div> </div> Here's the correspondi ...

Is there a way to insert a label directly following a dropdown menu within the same table cell?

My goal is to include drop-down lists in a web page, so I decided to create a table structure using JavaScript. Firstly, I used the document.createElement() method to generate a table, table body, rows, and cells. Then, I proceeded to create select element ...

Issue with the navbar toggler not displaying the list items

When the screen is minimized, the toggle button appears. However, clicking it does not reveal the contents of the navbar on a small screen. I have tried loading jQuery before the bootstrap JS file as suggested by many, but it still doesn't work. Can s ...

Creating dynamic animations by shifting the hue of an image on a canvas

Recently, I've been exploring the world of canvas tags and experimenting with drawing images on them. My current project involves creating a fake night/day animation that repeats continuously. After trying various approaches like SVG and CSS3 filters ...

Unique randomly generated number assigned to each item

This script saves a single number in the local storage along with the timestamp of its generation. After 1 minute, the item is updated in the local storage and displayed on the HTML page. I'm trying to find a way to generate one unique number for eac ...

Is it possible to alter the page color using radio buttons and Vue.js?

How can I implement a feature to allow users to change the page color using radio buttons in Vue.js? This is what I have so far: JavaScript var theme = new Vue({ el: '#theme', data: { picked: '' } }) HTML <div ...

Adjusting the size of a React element containing an SVG (d3)

In my simple react app, I have the following component structure: <div id='app'> <Navbar /> <Graph /> <Footer /> </div> The Navbar has a fixed height of 80px. The Footer has a fixed height of 40px. The Graph i ...

Creating equal height for two element children using CSS

As I construct a pricing table, I'm faced with the challenge of ensuring that the child elements within each row are of equal height. The website is built on WordPress and utilizes a page builder, resulting in the row fields being positioned different ...

Troubleshoot: Issues with Hover Highlight Feature in Bootstrap 4 Tables

After following the example from Bootstrap's site, I noticed that when adding the class table to my table tag, it changes the appearance. However, upon adding the table-hover class, there is no noticeable difference in the look and feel. Both lines of ...

CSS - Negative Margins Leading to Horizontal Scrolling Issue in Mobile Viewport

I’m working on some HTML and CSS code that looks like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= ...

printing not displaying colors

Is there a way to maintain the colors while printing my HTML page to PDF? <table class="table table-responsive table-striped"> <thead> <tr> <th>Elev</th> <th>Session n ...

I'm currently working with Bootstrap 5. Is there a technique available to reposition the elements within a div without relying on padding or margin properties?

Developing a Website: <!DOCTYPE html> <html lang="en" class="h-100"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" ...

What is the mechanism through which React manages the use of the "-" symbol within

Can someone help me with a CSS block? .button-set { /* CSS styles */ } What is the best way to apply this to a JSX element using the className attribute? ...

Create a custom navigation bar using Bootstrap styling

I am currently attempting to create a unique Navigation Bar design using bootstrap https://i.sstatic.net/HDGFw.jpg Here is the code snippet I am working on: <div class="navbar-header"> <button type="button" class="navbar-toggle" data- ...

What methods can I employ with JavaScript to catalog data collected from an HTML form?

Currently, my form requires users to input a username that cannot start or end with a period (.). I have implemented some code but I believe there is an issue with the .value[0] parts. //Checking Username if (document.getElementById("uName&quo ...

Utilizing the power of JavaScript/JQuery to showcase a compilation of all input values within an HTML form

I'm struggling to showcase all the input values from my HTML form on the final page before hitting the "submit" button. Unfortunately, I am facing a challenge as the values are not appearing on the page as expected. Despite several attempts, the valu ...

Designing interactive elements that conceal individual paragraphs

I am working on a project that involves 3 buttons and 3 paragraphs. My goal is to create a JavaScript function that will hide all paragraphs except the one with the same letter as the button clicked. I want to achieve this by applying a CSS rule that adds ...

What is the best way to use the cursor-pointer property in combination with a (click) event handler

<i class="cursor-pointer" (click)="sort()"></i> Our development team is grappling with numerous repetitive class definitions such as this one. I wanted to find a more efficient way to automatically add the cursor pointer style whenever a (clic ...