Learn CSS Flexbox by Building a Photo Gallery- Step 9 question

I am confused about something after completing step 9 of the flexbox tutorial (changing the box-sizing property from content-box to border-box). After doing so, all of my img elements (including their borders) fit within the border of their div parent element (see below photos).

My CSS for this is:

  • (*, not bullet point) {
    box-sizing: border-box;
    }

.gallery {
border: 5px solid red;
width: 50%;
}

img {
width: 100%;
border: 5px solid blue;
padding: 5px;
}

However, I don’t understand how the border of the img elements would fit inside the border of the div element (.gallery) if the display is set to border-box and the width of the img elements is set to 100% of its div container. If the width of the img elements is 100% of the width of its div element, wouldn’t the img elements’ borders overlap with the div border? i.e. wouldn’t the width of the img elements (including their border) be the same width as the div element? Which means the img border would cover the div border (at least horizontally)?

I clearly am experiencing a misunderstanding here. But I can’t figure out how the .gallery div element appears wider than the img elements if the img elements are set to 100% of the width of the div. And since the display is set to border-box, the width of the div should not increase by adding a border to it.

Edit: is it simply because child elements are always set to fit inside their parent/container elements? i.e. if I set the width of an element to 100%, it will be set to the largest width it can be without overlapping with its parent element’s border? In that way the border of the container element somewhat functions as padding for the child element?

These are good questions. It’s slightly complicated, but in this instance the 100% means 100% of the parent’s content box. The content box does not include the border, so that’s why the image border is right inside of the div border. The content box also does not include any padding. Try adding padding: 10px to .gallery and see what happens.

If you are very curious you can read more about this at MDN: Layout and the containing block.

1 Like