我正在尝试使用HTML和CSS创建一个中央菜单,创建了菜单,但是现在我不明白如何将菜单放在页面的中央。

我试图用margin:auto修改topnav类,但是什么也没发生。

这是我的代码:

的HTML

    <div class="topnav" id="myTopnav">
        <a href="#home">Home</a>
        <a href="#news">News</a>
        <a href="#contact">Contact</a>
        <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction(`enter code here`)">&#9776;</a>
    </div>


的CSS

.topnav {
  overflow: hidden;
  background-color: #333;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {display: none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }

}


JS

<script>
function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}`enter code here`
</script>

最佳答案

如果我理解正确,则希望文本水平居中。

为此,您只需要添加text-align:center;即可。到topnav。

您使用的属性,margin:自动;将使导航栏本身(而不是其内容)居中,但没有任何影响,因为它已经占据了屏幕的整个宽度。

.topnav {
  overflow: hidden;
  background-color: #333;
  text-align:center;
}


Jsfiddle:https://jsfiddle.net/aud5bsq4/7/

08-15 19:56
查看更多