【问题标题】:How to have a list, an image and a h1 all in the same line (but aligned differently)如何在同一行中有一个列表、一个图像和一个 h1(但对齐方式不同)
【发布时间】:2021-07-14 01:39:09
【问题描述】:

我有一个 img(徽标)、一个 h1(网站名称)和一个 ul(导航栏)。 目前, img 和 h1 在同一行(都左对齐),这是我想要的。我的 ul 向下一行,我希望它在 h1 旁边,向右对齐。我怎样才能做到这一点?我试过 display: inline-block;宽度:自动;但这没有用。

HTML:

<header>
    <img src="/images/logo.png" alt="Logo" id="logo">
    <h1>Title</h1>
    <nav>
        <ul>
            <li><a href="index.html" class="nav-link">Home</a> |</li>
            <li><a href="gallery.html" class="nav-link">Gallery</a> |</li>
            <li><a href="about.html" class="nav-link">About</a></li>
        </ul>
    </nav>
</header>

还有 CSS:

h1 {
    display: inline-block;
    width: auto;
}

ul {
    list-style: none;
    display: inline-block;
    width: auto;
}

ul li {
    display: inline;
}

我真的很感激一些帮助,我被困在这里太久了

【问题讨论】:

    标签: html css alignment html-lists


    【解决方案1】:

    您可以使用简单的 css 网格来做到这一点,只需添加标题和导航 css 类

    header {
      display: grid;
      grid-template-columns: repeat(2, auto) 1fr;
      align-items: center;
    }
    
    nav {
      justify-self: end;
    }
    
    h1 {
        display: inline-block;
        width: auto;
    }
    
    ul {
        list-style: none;
        display: inline-block;
        width: auto;
    }
    
    ul li {
        display: inline;
    }
    <header>
        <img src="/images/logo.png" alt="Logo" id="logo">
        <h1>Title</h1>
        <nav>
            <ul>
                <li><a href="index.html" class="nav-link">Home</a> |</li>
                <li><a href="gallery.html" class="nav-link">Gallery</a> |</li>
                <li><a href="about.html" class="nav-link">About</a></li>
            </ul>
        </nav>
    </header>

    【讨论】:

    • 谢谢,我不知道我怎么错过了这么简单的解决方案。
    • 不客气,你可以借助 grid 或 flex 解决很多定位问题 :)
    猜你喜欢
    • 1970-01-01
    • 2015-11-24
    • 2011-04-14
    • 1970-01-01
    • 2013-02-28
    • 2011-11-09
    • 2021-12-14
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多