0
<ul>
    <li>List1</li>
</ul>

and simple CSS:

li {
    background-color:pink;
    padding:5px;
    margin:40px;
    }
    
ul {
    list-style-type:none; 
    background-color:blue;
}

Why isn't the vertical margin working? Margin-right/left work, but why isn't the top/bottom working? "list-item" should be a block-level element, right? So, why isn't the vertical margin respected then?

Height seems to be working, but vertical margin doesn't.

However, if you add a second "li" sibling,

<ul>
    <li>List1</li>
    <li>List2</li>
</ul>

and add margin to both,

li {
    background-color:pink;
    padding:5px;
    margin:50px;
    }

the top margin of "list2" and the bottom margin of "list1" collapse, but create space nontheless, which means they worked, however, the bottom margin of "list2", and the top margin of "list1" still don't work. Why?

NOTE: I know that i can make the list-item into an inline-block, and the vertical margins would be respected, but my question is, why aren't they respected NOW.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Does this answer your question? [How can I set margin top/bottom to a li?](https://stackoverflow.com/questions/39041052/how-can-i-set-margin-top-bottom-to-a-li) – esqew Sep 11 '20 at 18:08
  • Maybe that's the default behavior of `ul`.You can try adding `padding-top: 40px;` and `padding-bottom: 40px;` to see if it solves your problem. – Tariqul Islam Sep 11 '20 at 18:13
  • @esqew No. I specifically highlighted in bold the Note at the end to avoid this type of answers. –  Sep 11 '20 at 18:57

1 Answers1

-1

Margin for li is working (as it is a block level element). The issue is -- you don't just see it.

* {margin:0; padding: 0;}

ul {
    list-style-type:none; 
    background-color:blue;
    border: 1px solid green;
}

li {
    background-color:pink;
    margin:40px;
}
    
<ul>
    <li>List1</li>
</ul>
Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • I am confused. Why is the margin working here? What do you mean i don't see it? Then why do i see it on your answer? If the margin was working, it would've pushed aside the parent borders like it does in your answer. –  Sep 11 '20 at 18:59
  • Margin was there. Just add `* {margin:0;padding:0}`, so that default-browsers CSS is removed, and you may just see your code and its affects. – Deadpool Sep 11 '20 at 19:28
  • Setting the margin and padding to 0 of the parent container did not change anything. It was adding a border to the parent container (ul) that for some reason made the margin of the list-item work. I have no idea why. Do you have any idea why? Margins don't inherit the background-color of the element, so why does the margin have a background-color, and why does adding a border to the parent makes the vertical margin of the child-elements work? Without the border, the vertical margin doesn't work. –  Sep 11 '20 at 19:50