CSS Border Gaps Between Parent and Child Elements
Unwanted Gaps When Applying Borders
When working with CSS layouts, you might encounter unexpected gaps between parent eleemnts and their children after applying borders. This issue persists even when setting child elements to display: block.
Problematic Code Example
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Border Gap Issue</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: #f0f0f0;
}
.container {
display: flex;
flex-direction: column;
}
.nav-item {
width: 120px;
border: 2px solid #333;
border-radius: 8px;
overflow: hidden;
padding: 0;
margin: 10px;
background-color: white;
box-sizing: border-box;
font-size: 0;
}
.nav-item a {
font-size: 16px;
display: block;
text-align: center;
color: #333;
padding: 10px;
}
.nav-item a:hover {
color: white;
background-color: #3498db;
}
</style>
</head>
<body>
<div class="nav-item container">
<a href="#">Programming</a>
<a href="#">Programming</a>
<a href="#">Programming</a>
<a href="#">Programming</a>
<a href="#">Programming</a>
<a href="#">Programming</a>
</div>
</body>
</html>
Troubleshooting Process
After removing the border, the gaps disappeared, which indicated the border was causing the issue. Further testing revealed:
- Reducing border to 1px eliminated the left gap, but the bottom gap remained
- Increasing border to 3px created gaps on the right side aswell
- Setting border to 12px removed all gaps
Root Cause Analysis
The border occupies space but doesn't fill it with the parent container's background color, creating visible gaps.
Solution
Using border values that are multiples of 0.16px prevents gaps at 100% zoom. The value 0.01rem (approximately 0.16px) works well when combined with:
box-sizing: border-box;
This ensures borders are included in the element's total width and height calculations. While 0.06rem is closest to 1px, using 0.01rem or 0.1rem can simplify calculations and reduce cognitive overhead.
Note: This approach may still produce gaps at zoom levels like 125%, but this is generally not a significant concern for most applications.