Home > Web Front-end > CSS Tutorial > Why Do My Inline-Block List Items Have Unwanted Margins Even With `margin: 0`?

Why Do My Inline-Block List Items Have Unwanted Margins Even With `margin: 0`?

DDD
Release: 2024-11-30 17:13:15
Original
488 people have browsed it

Why Do My Inline-Block List Items Have Unwanted Margins Even With `margin: 0`?

Unwanted Margin in Inline-Block List Items

Problem

I'm encountering an issue where list items that are set to display: inline-block have an unwanted margin around them, even though the CSS rule for margin is set to 0.

HTML:

<ul>
  <li><div>first</div></li>
  <li><div>first</div></li>
  <li><div>first</div></li>
  <li><div>first</div></li>
</ul>
Copy after login

CSS:

ul {
  padding: 0;
  border: solid 1px #000;
}
li {
  display: inline-block;
  padding: 10px;
  width: 114px;
  border: solid 1px #f00;
  margin: 0;
}
li div {
  background-color: #000;
  width: 114px;
  height: 114px;
  color: #fff;
  font-size: 18px;
}
Copy after login

Solution

This problem is caused by the display: inline-block property. Here are two solutions:

  1. Change display: inline-block to float: left:

    • CSS:

      li {
        float: left;
      }
      Copy after login
  2. Remove whitespace between list items:

    • Remove the newlines between the

    • tags and block the end tags and begin tags together:

      • HTML:

        <ul>
          <li><div>first</div></li><li><div>first</div></li><li><div>first</div></li><li><div>first</div></li>
        </ul>
        Copy after login

Note:

inline-block renders a 4px margin to the right of each element. To avoid this, it's recommended to either use float or avoid whitespace between list items.

The above is the detailed content of Why Do My Inline-Block List Items Have Unwanted Margins Even With `margin: 0`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template