When can % work for height and width and when cant it?

body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    min-width: 100vw;

.container {
    border: 1px solid red;
    height: 500px;
    width: 700px;
    background: url('./images/3.jpg') no-repeat center center/cover;

Why does the height: 500px; and width: 700px; work but using a percentage in this scenario wont work? Shouldn’t the .container class just take defaults from the body? making it say 50% width and height shouldn’t that make it 50% of the page since 100vh and 100vw are assigned to the body.

I have always just used px when it doesn’t work but today I thought I would ask to finally get an answer for this lol.

Also well I’m here I’ll also ask why background: url works but background-image doesn’t in this case as well.

I’ve done HTML and CSS for a while but sometimes I still get tripped up on these little things, I usually just do it a different way to get the same result but may as well try to get some answers.


This might seem confusing I agree, but when you assign min-height it doesn’t mean automatically height property is getting assigned (which looks like a bug to me) and so you’re ending up with body with default height (which is auto) and min-height: 100vh; at the same time. When height of a child is being calculated parser will not go “Oh, by the way, what’s the min-height of parent”, it will just see auto to will go from there :slight_smile:

That’s why you always have to specify height as well when using min-height

ADD: In short, min-height doesn’t set height of the element

1 Like

So when min-height and max-height are used best case to avoid any issues is to also add a height and width in the code block?

When I use height and width it does in fact work. Thought I tried that.

So as I gather it ends up as auto height when min-height is used which in turn doesn’t let the .container class work? min-height and min-width does help a lot with responsiveness I find though.

Also the second question I figured out and it was kind of just something I missed when originally typing.

background: is the shorthand property for all background style properties at once, color, image, size, repeat. Therefore it needs the no-repeat center center/cover for proper positioning.

background-image: is targeting in on just the image so no need to set the other properties at the end of the code. no-repeat center center/cover are not needed at the end of background-image and it is in fact breaking that code. Need to set these key value pairs separately.

Yes background is one of the shorthand properties. You can learn about them here: https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties