intropedro
intropedro

Reputation: 2804

Dynamic height auto-resize with css

As I can have a div with two children inside, one of which is not shown (display: none) and the other occupies the entire space of the father, but when I tell javascript to display the hidden the other autoredimensiones to space left without using javascript?

html:

<div class="parent">
    <div class="child1" id="id1">
    </div>
    <div class="child2">
    </div>
</div>

css:

.parent {
    height: 200px;
    background-color: red; 
}
.child2 {
    height: 100%;
    background-color: blue;
}
.child1 {
    display:none;
    height: 50px;
    background-color: green;
}

javascript:

var myDiv = document.getElementById('id1');
myDiv.style.display="block";

Upvotes: 0

Views: 2380

Answers (1)

David Thomas
David Thomas

Reputation: 253318

This can't be achieved with pure CSS, but if you're okay about adding a little more JavaScript (in order to add a class-name), then it can be achieved:

Amended JavaScript:

var myDiv = document.getElementById('id1');
myDiv.style.display = "block";
myDiv.className += ' nowShown';

Appended CSS:

.child1.nowShown {
    float: left;
    width: 50%;
}

.child1.nowShown + .child2​ {
    display: inline-block;
    width: 50%;
}​

JS Fiddle proof-of-concept.

Otherwise it's not possible, simply because CSS lacks the capacity to determine the visual/display state of an element. If it had a :visible pseudo-class then it'd be possible, but without such, as currently, it's sadly not.


Adapted the above proof-of-concept to implement a slightly less-than-concise toggle:

function showDiv1() {
    var myDiv = document.getElementById('id1'),
        cN = myDiv.className;
    myDiv.style.display = "block";

    if (cN.match(/nowShown/)){
        myDiv.className = cN.replace(/nowShown/,'');
        myDiv.style.display = 'none';
    }
    else {
        myDiv.className += ' nowShown';
    }
    nC = myDiv.className;
    myDiv.className = nC.replace(/\s{2,}/,' ');
}

document.getElementsByTagName('button')[0].onclick = function(){
    showDiv1();
};​

JS Fiddle demo.

Upvotes: 2

Related Questions