Stephen R
Stephen R

Reputation: 3907

CSS3 child combinator with *

I'm trying to use a CSS3 child combinator ( > ) to set any child of a div to max-width: 100%;. In combination with box-sizing:border-box;, I'm trying to set it so that any content of a div is never larger than the containing div.

* {
    box-sizing: inherit;
}
html {
    box-sizing: border-box;
}
div > * {
    max-width: 100%;
}

Now I have an image inside a div:

<div style="width: 70%;">
    <img src="foo" width="750" height="200" />
</div>

If 750 pixels is wider than the div's 70% width, the image breaks out of the div. If I change the CSS to:

div > img {
    max-width: 100%;
}

...then the image shrinks to fit the div (which is what I want). What am I missing here? Is there a known issue where the wildcard * just doesn't work in this situation?

Upvotes: 0

Views: 54

Answers (1)

Jonathan
Jonathan

Reputation: 6537

Child selector support (>) dates base to IE 7 and the universal selector (*) dates back to IE 7 as well (unless you are using a namespace)

For an image you will need a height of auto to prevent it from stretching.

* {
    box-sizing: inherit;
}
html {
    box-sizing: border-box;
}
div > * {
    max-width: 100%;
    height: auto;
}
<div style="width: 70%;">
    <img src="http://placehold.it/750x200" width="750" height="200" />
</div>

Upvotes: 1

Related Questions