我可以删除导航按钮之间的空格,使它们居中吗?我尝试在li a
中删除inline-block
,但我认为有些地方是错误的,我认为是问题display: inline-block
,但我不确定......
有人可以帮助我吗?提前谢谢。
nav ul {
text-align: center;
margin: 0px;
padding: 0px;
position: fixed;
width: 100%;
height: auto;
background: #b2bac9;
color: #090a0d; }
nav ul li {
margin: 0px;
padding: 0px;
display: inline; }
nav ul li a {
text-decoration: none;
display: inline-block;
padding: 16px;
text-decoration: none;
color: #fff;
background: red; }
nav ul li a:hover {
background: #949fb4; }
#tit {
position: absolute;
top: 100px;
left: 50%;
transform: translateX(-50%);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> nav </title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">The Project</a></li>
<li><a href="#">Forum</a></li>
</ul>
</nav>
<h1 id="tit" align="center"> I need to remove the balnk space between red buttons </h1>
</header>
</body>
</html>
发生这种情况的原因是,当使用带有inline-block
的元素时,它们的处理方式与文本中的单词相同。然后,元素之间的换行符和制表符将计为空格。
要修复它,只需将nav ul
设置为 display: table
:
nav ul {
display: table;
text-align: center;
margin: 0px;
padding: 0px;
position: fixed;
width: 100%;
height: auto;
background: #b2bac9;
color: #090a0d;
}
nav ul li {
margin: 0px;
padding: 0px;
display: inline;
}
nav ul li a {
text-decoration: none;
display: inline-block;
padding: 16px;
text-decoration: none;
color: #fff;
background: red;
}
nav ul li a:hover {
background: #949fb4;
}
#tit {
position: absolute;
top: 100px;
left: 50%;
transform: translateX(-50%);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> nav </title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">The Project</a></li>
<li><a href="#">Forum</a></li>
</ul>
</nav>
<h1 id="tit" align="center"> I need to remove the balnk space between red buttons </h1>
</header>
</body>
</html>
您还可以删除元素之间的所有空格,换行符和制表符(我不会重新评论),或者将Flexbox与justify-content: center
一起使用,如下所示:
nav ul {
display: flex;
justify-content: center;
margin: 0px;
padding: 0px;
position: fixed;
width: 100%;
height: auto;
background: #b2bac9;
color: #090a0d;
}
你可以阅读更多关于它的信息: CSS-Tricks: Fight the Space Between Inline Block Elements
处理这个问题有一个奇怪的小技巧,只需删除<li>
元素中的空格:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> nav </title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#">Home</a></li><!--
--><li><a href="#">The Project</a></li><!--
--><li><a href="#">Forum</a></li>
</ul>
</nav>
<h1 id="tit" align="center"> I need to remove the balnk space between red buttons </h1>
</header>
</body>
</html>
请参阅 JSFiddle