Search code examples
htmlcsssassbootstrap-4styling

Can I make my div inherit height and position from one div and width from another?


I have a div (div1) inside some other divs. Now I want this div to have the same width as the body (take up full width of display), but always have the same height and position as its parent (div2). I've tried using position: absolute; on this div (div1). Then I can either

  • set body to position: relative; and have div1 take up 100% width, but now I'm having trouble making the height always follow div2.
  • or set the parent (div2) to position: relative; and have div 1 take up 100% height, but now I can't make it follow the width of body.

It would be cool if CSS had the option of saying:

.div1 {
height: 100%(.div2); 
width: 100%(body); 
position: 0(.div2); 
}

Or something like that

JSFiddle with the relevant bits: https://jsfiddle.net/Hamleyburger/fqe5o46c/1/#&togetherjs=K02DaSO2nR

  • What I want is the div ".selectable" to have a div (inside?) that shows on hover and fits the heights of ".selectable" (parent) and the entire width of the body.

Extra, maybe relevant info: I'm using Bootstrap and (Jinja2) templating. All the divs so far are taking their base widths from a wrapper container (.main) in my base template that I've set to be (responsively) narrower than body. If I were to remove .main div I would have to set width on many individual divs. That would solve it (I could make all the divs that aren't div1 narrower), but it wouldn't be very DRY. I'm using SASS, if that helps.


Solution

  • It's possible to force a div to fill the whole viewport width using vw. It's a bit weird though:

    body,
    html {
        margin: 0;
        padding: 0;
    }
    
    .outer {
        width: 300px;
        height: 300px;
        background-color: #eeeeee;
        margin: 0 auto;
        position: relative
    }
    
    .inner {
        width: 100vw;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.1);
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
    <div class="outer">
        <div class="inner"></div>
    </div>

    I'd recommend to make your outer div full width and give the inner one a specific width:

    body,
    html {
        margin: 0;
        padding: 0;
    }
    
    .outer {
        width: 100%;
        background-color: #eeeeee;
        position: relative
    }
    
    .inner {
        width: 300px;
        height: 300px;
        margin: 0 auto;
        background-color: rgba(0, 0, 0, 0.1);
    }
    <div class="outer">
        <div class="inner"></div>
    </div>