1

I have two pieces of similar code-

Code snippet 1-

<div class="section-2">
        <div class="about">
            <h1 style="text-align: center;margin-top: 50px;">ABOUT</h1>
            <hr style="height:5px;width:5%;border:none;color:#333;background-color:#333;" />
        </div>
</div>

Output snippet 1

Code snippet 2-

<div class="section-3">
        <div class="projects">
            <h1 style="text-align: center;margin-top: 50px;">PROJECTS</h1>
            <hr style="height:5px;width:5%;border:none;color:#333;background-color:#333;" />
        </div>

</div>

Output snippet 2

As you can see,the margin-top styling of the h1 tag doesnot work in snippet 2. Why is this happening?

Note:- No css styling has been applied to any of the divs.

  • 2
    You might want to read up about margin collapse: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing – Terry Mar 30 '20 at 06:56
  • Is this all of your css because when i put in both of those snippets i don't even get the top line on the About – ShrewdStyle Mar 30 '20 at 07:07
  • @ShrewdStyle,The top line is from another section which does not have a margin bottom property. So this should be all the code. – Sushmit Chakraborty Mar 30 '20 at 07:16

1 Answers1

2

There are two things you can do with this to get it working, you will only get a margin the same width of your div, so you can either make the .section-2 div and the .section-3 div a set width

.section-2 {
  width: 250px;
  margin: 50px auto;
  border-top: 6px solid blue;
}

which i do not recommend as your content will now be limited to what it can fit in, or you can make a css class and call it top line or whatever you want, and then just include that, shown below

<div class="section-2">
      <div class="about">
        <div class="top-Line"></div>
        <h1 style="text-align: center;">ABOUT</h1>
        <hr
          style="height:5px;width:5%;border:none;color:#333;background-color:#333;"
        />
      </div>
    </div>
    <div class="section-3">
      <div class="top-Line"></div>
      <div class="projects">
        <h1 style="text-align: center;">PROJECTS</h1>
        <hr
          style="height:5px;width:5%;border:none;color:#333;background-color:#333;"
        />
      </div>
    </div>
.top-Line {
  width: 250px;
  background-color: rgb(11, 143, 167);
  height: 6px;
  margin: 50px auto;
}

to make this look as you wanted i have also removed the margin-top from your HTML on your H1s

ShrewdStyle
  • 500
  • 2
  • 5
  • 14