Simple CSS Question [ SOLVED ]

I have a blue box and a title in that box.

<div class="main-blue-box">

	<div class="title">Dr. Norman Borlaug</div>

</div>

.main-blue-box {
	background-color: #EEEEEE;
	width: 85%;
	margin: 3rem auto;
}

.title {
	font-size: 3.5rem;
	text-align: center;
}

I gave the blue box a margin-top of 3 rem

The title goes to the top of the box like it should, but when I give the title a top margin, it is set relative to the top of the page, not the top of the box. Why doesn’t my title register the box as the next element to hit margin against? It’s as if I have to set the title to a margin greater than 3rem to overcome the margin-top of the blue box it’s in. Why is this happening?

Try pasting some code so we can run it and give you better advice. Use the markdown triple-backticks ``` before and after your code to make it look like:

.blue-box{
  margin-top: 3rem
}

Ok can do, just edited my post :slight_smile:

pasted your code into a jsfiddle and it looks good to me. Perhaps provide a link showing the problem, as vipatron said, it’s easier to investigate that way.

Okay, I see your issue now: You are running into collapsing margins. Basically, the biggest vertical margin between two adjacent elements is honored by default. You can change this default behavior if you wish, but it’s set by default that way on purpose because it will be more useful in more situations.
https://www.sitepoint.com/collapsing-margins/
On W3, there’s a testing suite where you can play around with it: (Look for the heading Margin Collapse halfway down the page)
https://www.w3schools.com/cssref/pr_margin.asp

1 Like

Thank you very much, that helped a lot :smiley:

Do you know if this problem is automatically fixed if I were to apply something like normalize.css?

I am not familiar with that stylesheet, but the sitepoint article has ways of doing that. If you wanted that gray box (that you have classed .main-blue-box) to have vertical space around the text “Dr. Norman Borlaug”, you want padding, not margin. Otherwise, if you want white space on the top of the gray box, I don’t see why you can’t just set the margin you want on one of the divs.

1 Like

Hi @MarcusSchumacher, if you could, click the checkbox next to the reply where I answered your question. That’s how the system keeps track of such things. The checkbox should turn green afterwards.