如何将 h1 分组并列表在一起?

我正在尝试制作一个标题菜单,其右侧有水平列表(导航区域或菜单),左侧有 h1(网站名称)(两者都使用浮动标签来执行此操作)。我尝试使用 header、nav 和 div 标签将两者分组在一起,但没有任何效果。h1 和 ul 标签就像是分开的,而不是分组的。当我给分组标签(Div,标题,导航)背景颜色时什么也没有发生,但是当我给它一个颜色时:....里面的所有文本都会改变颜色,所以至少可以。

请帮我将 h1 和 ul 分组在一起。


.header {

  width: 100%;

  background-color: aquamarine;

  color: red;

}


h1 {

  float: left;

}


ul {

  float: right;

  list-style: none;

  display: block;

}


ul li {

  display: inline-block;

}

<html>


<body>

  <header class="header">

    <h1>website name</h1>

    <ul>

      <li>Home</li>

      <li>contact</li>

    </ul>

  </header>

</body>


</html>


SMILET
浏览 73回答 3
3回答

萧十郎

正如MDN - CSS Float所说如上所述,当元素浮动时,它会从文档的正常流程中取出(尽管仍然保留为文档的一部分)。它向左或向右移动,直到接触到其包含框或另一个浮动元素的边缘。从父上下文中删除浮动意味着使用旧式CSS hacks(例如clearfixes),以使父元素“意识到”包含的浮动元素。因此,为了防止出现 Float 警告,只需重复使用更好但更简单的方法:CSS 弹性display: flex;.header {  background-color: aquamarine;  color: red;  display: flex;}ul {  list-style: none;  display: flex;  margin-left: auto;}li{  padding: 1em;}<header class="header">  <h1>website name</h1>  <ul>    <li>Home</li>    <li>Contact</li>  </ul></header>

繁星淼淼

由于您使用的是浮动,因此您需要使用称为clearfixhack 的东西。如果没有,你可以将它们制作为display: inline-block.header {&nbsp; width: 100%;&nbsp; background-color: aquamarine;&nbsp; color: red;}h1 {&nbsp; float: left;}ul {&nbsp; float: right;&nbsp; list-style: none;&nbsp; display: block;}ul li {&nbsp; display: inline-block;}.clearfix::after {&nbsp; display: block;&nbsp; content: "";&nbsp; clear: both;}<html><body>&nbsp; <header class="header clearfix">&nbsp; &nbsp; <h1>website name</h1>&nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; <li>Home</li>&nbsp; &nbsp; &nbsp; <li>contact</li>&nbsp; &nbsp; </ul>&nbsp; </header></body></html>

婷婷同学_

使用浮动是相当繁琐的工作,使用 Flexbox 制作导航栏。.nav-wrapper{&nbsp; width:100%;&nbsp; display:flex;&nbsp; justify-content:space-between;&nbsp; align-items:center;}.list-wrapper{&nbsp; width:50%;&nbsp; display:flex;&nbsp; justify-content: space-evenly;&nbsp; align-items:center;}<div class="nav-wrapper">&nbsp; <h1>Header</h1>&nbsp; <ul class="list-wrapper">&nbsp; &nbsp; <li>Home</li>&nbsp; &nbsp; <li>Contact</li>&nbsp; &nbsp; <li>About us</li>&nbsp; </ul></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5