简体   繁体   中英

How can I set the width of an element based on the width of another element?

I am attempting to figure out how to make the width of an element dynamic.

I have a side bar with width: 350px and then when a full* width modal comes in, that sidebar should still be visible.

This is what the modal have:

    position: fixed;
    top: 0;
    right: 0;
    z-index: 1050;
    width: 73%;
    height: 100%;
    outline: 0;

With the width set 73%; it works for now, the sidebar is always visible, but what will happen if the sidebar changes its width?

I am using React. I guess this should be done with JavaScript.

What should I do to achieve what I need?

You can Use calc() ( Just css ) like:

width: calc(100% - 350px);

Where 350px is the width of the sideBar.

If the width of the sideBar changes, you'll need to get the new width and replace the 350px with a variable holdign the value of that new width.

I feel like you probably just need to get the width of that sidebar, get the width of the overall window, and do some simple math to figure out what you need to set the width of your modal to. However, you also need to account for the window resizing. So, it would likely be something similar to this.

setModalSize();

$('window').on('resize', function() {
    setModalSize();
}

function setModalSize() {
    var windowWidth = $('window').width(),
        sidebarWidth = $('#sidebar').css('width');

    $('#modal').css('width', (windowWidth - sidebarWidth));
}

There are a couple of different ways to pull the width of an element. I've included them in this quick code sample.

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