I have two divs:
S
-
This is due to margin collapsing:
Top and bottom margins of blocks are sometimes combined (collapsed)
into a single margin whose size is the largest of the margins combined
into it, a behavior known as margin collapsing.
This is resulting in the parent element reverse-inheriting the child element top margin.
You can prevent this by adding
before the child element
Demo Fiddle
....or applying any of the below to the parent:
- float: left / right
- position: absolute
- display: inline-block
Adding display:inline-block;
to the parent likely being the preference if it is set to have a width to 100%
Demo Fiddle
讨论(0)
-
Just add some top-padding to the parent element. even 1px and it will fix it.
讨论(0)
-
just use box-sizing: border-box;
on the parent and set the padding
there instead of margin-top
. It will help you keep consistent spacing on all sides anyways
JSFIDDLE
讨论(0)
-
I would actually argue that this answer is better:
https://stackoverflow.com/a/49075574/2387316
Yes, I know it's my own answer, but I think it's important that we don't add random bits of padding, change box-sizing for no reason, add spurious elements to the DOM, or change display/padding simply to fix a display issue. Those solutions all cause problems on their own: SEO is worse, unpredictable box-sizing behavior when trying to do something else, annoyance caused by positioning and display changes, etc. This solution is good for SEO, is scalable, and has no other tangible effect when trying to do other things with your elements.
讨论(0)