Rothko Paining Step 20

Hello. I had a question about applying the “margin” property to a “div” element within a “div” element.

Here is the code:

  1. HTML Code
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Rothko Painting</title>
    <link href="./styles.css" rel="stylesheet">
    <div class="frame">
      <div class="canvas">
        <div class="one"></div>
  1. CSS Code
.canvas {
  width: 500px;
  height: 600px;
  background-color: #4d0f00;

.frame {
  border: 50px solid black;
  width: 500px;
  padding: 50px;
  margin: 20px auto;

.one {
  width: 425px;
  height: 150px;
  background-color: #efb762;
  margin: 20px, auto

When I give the class “.one” a top and bottom margin of 20px, I would expect a 20px space to be created between the top edge of “.one” and the top edge of “.canvas.” However, the top edge of “.one” is flush with the top edge of “.canvas” and the white-colored padding-top for “.frame” seems to increase.

Image of “margin: 20px auto;” applied to “.one”:

Is this normal behavior?

Thank you for your help. I’m new to the forum and I hope my question makes sense. Let me know if there is anything I can improve.

Margins don’t automaticlly create padding, they need something to push against. The .canvas div doesn’t have any top padding, so there is nothing to push against and thus the top of .canvas and .one stay flush. That doesn’t mean the top margin for .one isn’t pushing against something. See below.

That increase is actually the top margin for .one. The best way to see this is to use the browser’s dev tools to inspect .one. You’ll see that .frame has padding on all four sides and so the top margin for .one is pushing against that padding, which causes .one to move downwards the amount of it’s top margin. But since margins don’t have color, you just see the white background of .frame increase.

1 Like

Thank you so much for your reply. Really appreciate it!

So would it be correct to understand that two margins will collapse when they are vertically adjacent with each other? And that one way to deal with it would be to add padding so that there is something to push against?

Top and bottom margins collapse. Right and left margins do not. If you have a top element with 30px bottom margin and a bottom element with 20px top margin and you want the distance between them to be a combination of both of their margins (50px) then yes, you need to have something between them that they can each push against so they don’t collapse. But that thing in between them will need to have at least 1px of height (which could be 1px of padding), so the actual distance between them will be 51px.

That makes sense. Thank you again for the detailed reply.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.