html - 导航栏 - 当我添加图像 Flexbox 初学者问题时,中心 ul 不起作用
问题描述
我想创建一个简单的导航栏,我希望它居中。它有效,但是当我在 ul 上方添加图像时,列表不再居中,我不知道为什么。我使用 justify-content center 将标题元素居中。
为了使徽标居中,我将左右边距更改为自动,并在其上设置 20% 的宽度。看起来图像有问题,但我不确定。
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap');
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
body{
font-family: "Montserrat",sans-serif;
font-weight: 500;
}
header{
display: flex;
padding: 25px 10%;
justify-content: center;
}
.logo{
display: block;
margin: 0 auto;
width: 20%;
}
.nav__links li{
display:inline;
padding: 0 15px;
}
.nav__links li a{
color:#000000;
text-decoration: none;
transition: 0.3s;
}
.nav__links li a:hover{
color: rgb(0, 0, 0,0.8);
}
<!DOCTYPE html>
<head>
<title>Navbar</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<nav>
<img class="logo" src="https://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png"
alt="google">
<ul class="nav__links">
<li><a href="#">Plan your visit</a></li>
<li><a href="#">Exhibitions and events</a></li>
<li><a href="#">Art and artists</a></li>
<li><a href="#">Store</a></li>
</ul>
</nav>
</header>
</body>
</html>
解决方案
您可以通过添加它来解决居中问题。如果您希望 A 标签出现在中间,您需要将 display flex 专门应用于 UL 标签。所以你可以改变任何你想改变的方向。
ul{
display: flex;
justify-content: center;
}
header{
display: flex;
padding: 25px 10%;
justify-content: center; // and I added this because you want it right in the middle of the page.
}
|header // if you give a d-flex it only affects the same level of item, so only nav is affected
|nav // if you give a d-flex it only affects the same level of item, so img and ul is affected
|img
|ul // if you give a d-flex it only affects the same level of item, so elements within the li tag are affected.
|li
推荐阅读
- r - GGplot + Shiny 根据线的斜率改变线的颜色
- twilio - 多个外呼时,如何唯一识别通话
- django - Django获取模板中URL中路径的最后一部分
- c# - 如何在 Opencvsharp 中将提取的 Mat Contours 转换为位图?
- css - 部分背景正在围绕红色边框形成边框
- java - WSO2 IE 6.2.0 消息处理器停用问题
- java - 使用 getLoaderManager().initLoader 时出错
- parallel-processing - DiD 将匹配的治疗前数据与治疗后观察结果相结合
- javascript - 如何在下面的代码中使用 window.Function() 而不是 eval()?
- javascript - 需要使用 javascript 验证用户年龄是否大于 18 使用#joi 验证