简体   繁体   中英

set the width of a div to be the same as it's closest sibling

Is it possible to set the width of a div to be the same as it's closest sibling when the width on that div is width: auto; ?

In my jsFiddle you will see that I have a red, green and blue div. I want the blue div to adjust to the size of the green div (which is dynamic). So if the green div works out to be 200px then I want the blue div to be 200px.

Originally I thought I would be able to put the blue div inside the green one and set display: inline-block on the child, but this does not work.

So, if the content of the blue div increases then it won't push the width of the green div out (or the container div). How can this be achieved?

If you are willing to use JavaScript, you can adjust the width whenever the div you want to track changes. Using jQuery, it's simple:

$(document).ready(function() {
    // Function to sync the sizes of the divs
    function syncSize() {
        $("#banner_description").width($(".banner_secondary_title").outerWidth(true));
    }

    // Sync the size when a change is made
    $(".banner_secondary_title").resize(function(e) {
        syncSize();
    });

    // Initial sync after document setup
    syncSize();
});

Here is a fork of your jsFiddle with this code added, plus I added more text to the secondary title to expand it to show that it works.

Put the blue div inside the green div, add a really high negative margin-right ( -999em or something) to the blue div so that it doesn't stretch its parent green div.

Alternative solution: Put the blue div inside the green div, give the blue div a position:absolute . Give the green div a padding-bottom matching the height of the blue div. This will only work if the height of the blue div isn't dynamic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM