How to remove the space between inline-block elements in CSS

Topic: HTML / CSS« Prev|Next »

Answer: Remove space between the elements

The CSS display property with the value inline-block is very useful for controlling the dimensions as well as margin and padding of the inline elements. However, while using the inline-block visual formatting the whitespace in the HTML code creates some visual space on the screen. But you can get rid of it using the following simple techniques.

Solution 1: Remove Space Between Elements

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Remove Extra Space Between Inline-Block Elements</title>
  • <style type="text/css">
  •     ul {
  •         padding: 0;
  •         list-style: none;
  •     }
  •     ul li {
  •         display: inline-block;
  •         background: #ffa500;
  •         padding: 5px 20px;
  •     }
  • </style>
  • </head>
  • <body>
  •     <h2>Normal Behavior</h2>
  •     <ul>
  •         <li><a href="#">Home</a></li>
  •         <li><a href="#">About</a></li>
  •         <li><a href="#">Contact</a></li>
  •     </ul>
  •     <hr>
  •     <h2>After Removing Spaces</h2>
  •     <ul>
  •         <li><a href="#">Home</a></li><li><a href="#">About</a></li><li><a href="#">Contact</a></li>
  •     </ul>
  • </body>
  • </html>

Solution 2: Set Zero Font Size on Parent Element

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Remove Extra Space Between Inline-Block Elements</title>
  • <style type="text/css">
  •     ul {
  •         padding: 0;
  •         list-style: none;
  •         font-size: 0;
  •     }
  •     ul li {
  •         font-size: 16px;
  •         display: inline-block;
  •         background: orange;
  •         padding: 5px 20px;
  •     }
  • </style>
  • </head>
  • <body>
  •     <ul>
  •         <li><a href="#">Home</a></li>
  •         <li><a href="#">About</a></li>
  •         <li><a href="#">Contact</a></li>
  •     </ul>
  • </body>
  • </html>

You can also utilize the negative margin of 4 pixels like margin: -4px; on the inline-block elements to fix this problem, however the above two methods are more straightforward.


Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.