浮动不适用于文本和图像元素

时间:2019-01-29 23:18:31

标签: html css

我正在尝试使用HTML和CSS制作导航栏,但是我的CSS float: rightfloat: left语句无法正常工作,一切仍然在右侧。

.nav {
    width: 100%;
    text-align: center;
    display: flex;
    align-items: center;
    padding: 15px;
    overflow: hidden;
}

.nav-item {
    color: black;
    display: block;
    list-style-type: none;
    text-decoration: none;
    font-size: 1.2em;
    font-weight: bold;
    padding: 0px 8 px;
    text-transform: uppercase;
}
<div class="header">
        <div class="nav">
            <img src="img/logo.png" class="logo" width=50 height=50>
            <li class="nav-item"><a href="#" class="nav-item">Download</a></li>
            <li class="nav-item"><a href="#" class="nav-item">Contact</a></li>
        </div>
    </div>

2 个答案:

答案 0 :(得分:1)

正如评论中已经提到的那样,您需要将列表项包装在<ul>标记中。这既是正确的语法,也可以让您将整个链接列表移到右侧。

我还添加了justify-content: space-between来告诉flex将项目左/右对齐,并将display: inline-block到nav-item使其单行显示,而不是堆叠为块级元素。 / p>

.nav {
    width: 100%;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: space-between;
    overflow: hidden;
}

.nav-item {
    color: black;
    display: inline-block;
    list-style-type: none;
    text-decoration: none;
    font-size: 1.2em;
    font-weight: bold;
    padding: 0px 8px;
    text-transform: uppercase;
    margin-left: auto;
}
<div class="header">
        <div class="nav">
            <img src="img/logo.png" class="logo" width=50 height=50>
            <ul>
            <li class="nav-item"><a href="#" class="nav-item">Download</a></li>
            <li class="nav-item"><a href="#" class="nav-item">Contact</a></li>
            </ul>
        </div>
    </div>

答案 1 :(得分:0)

您几乎不错,请不要使用float,而可以使用display: flex并使用margin-left: auto将内容向左移动。

.nav {
    width: 100%;
    text-align: center;
    display: flex;
    align-items: center;
    overflow: hidden;
}

.nav-item {
    color: black;
    display: block;
    list-style-type: none;
    text-decoration: none;
    font-size: 1.2em;
    font-weight: bold;
    padding: 0px 8px;
    text-transform: uppercase;
    margin-left: auto;
}
<div class="header">
        <div class="nav">
            <img src="img/logo.png" class="logo" width=50 height=50>
            <li class="nav-item"><a href="#" class="nav-item">Download</a></li>
            <li class="nav-item"><a href="#" class="nav-item">Contact</a></li>
        </div>
    </div>