首页 > 解决方案 > 导航栏 - 当我添加图像 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>

标签: htmlcssflexbox

解决方案


您可以通过添加它来解决居中问题。如果您希望 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

推荐阅读