Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

html - How can I set margin top/bottom to a li?

Here is my code:

li {
  padding: 5px 4px 6px 7px;
  margin-top: 3px;
  margin-bottom: 3px;
  list-style: none;
}
li + li {
  border-top: 1px solid #eff0f1;
}
li:hover {
  background-color: #f7f8f8;
}
<ul>
  <li>something</li>
  <li>something else</li>
  <li>something else again</li>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is due to collapsing margins - from https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_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.

To get around this, I would wrap the content of the li in a span or div and put your original li padding on that, and then put the 3px margin as padding on your li instead:

li {
  list-style: none;
  padding: 3px 0; /* this is in place of your margin */
}
li + li {
  border-top: 1px solid #eff0f1;
}
li > span {
  display: block;
  padding: 5px 4px 6px 7px; /* this is you original li padding */
}
li:hover > span {
  background-color: #f7f8f8;
}
<ul>
  <li><span>something</span></li>
  <li><span>something else</span></li>
  <li><span>something else again</span></li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...