Optimizer Oscar
Optimizer Oscar

Reputation: 9

Is it possible to do this with only CSS, no JavaScript?

An outline of the scenario is that I have a div of class some-class which will either have 1 or 2 child divs. Whenever it has 1 I want that child div (div.some-class > div) to have width: 100%;, but whenever it has 2 I want them (div.some-class > div:nth-of-type(1), div.some-class > div:nth-of-type(2)) to have respective widths of 60% and 40%. I can't modify the HTML because it's generated by a content management system.

Is there a CSS hack that could give me this behavior?

Upvotes: 0

Views: 57

Answers (1)

Wex
Wex

Reputation: 15695

Sure, use display: table and the adjacent sibling selector.

body > div {
    display: table;
    width: 600px;
}

div > div {
    background: blue;
    height: 100px;
    display: table-cell;
}

div > div + div {
    background: red;
    width: 40%;
}
<div>
    <div></div>
</div>

<hr>

<div>
    <div></div>
    <div></div>
</div>

Upvotes: 3

Related Questions