如何在 html 中将标题文本居中放置在导航菜单的中间

新手上路,请多包涵

我想知道如何将我写在我创建的导航菜单中心的标题文本居中,文本已经居中但它居中在导航菜单的顶部,而不是在中间,这正是我需要的。

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<style>
    body {margin:0;}
    .Header {
        z-index: 100;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        background-color: #000000;
        height: 70px;
    }

    @media screen and (max-width:680px) {
        .Header.responsive {position: relative;}
        .Header.responsive li.icon {
            position: absolute;
            right: 0;
            top: 0;
        }

    }
    @media (max-width: 960px){
    .Header .headerLogo{
        display: inline-block;
        width: 86px;
        height: 15px;
        margin-top: 17px;
        margin-left: 6px;
    }
    }
</style>
</head>
<body>

<div class="Header" id="myHeader">
    <a class = "headerLogo">
    <header><center><i><font size = "6" face = "verdana" color = "white">Lunation Boards</font></i></center></header>
    </a>
</div>
</body>
</html>

原文由 nenur 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 380
2 个回答

您有三个选项, _其中前两个选项更可靠_。

第一个选项使用 flex-box 使项目水平和垂直居中。

 div {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: blue;
}

text {
  background: orange;
}
 <div>
   <text>Centered horizontally and vertically</text>
</div>

第二个选项不是使用 flex-box,而是使用父元素的相对位置,子元素的绝对位置,以及 transform: translate(X, Y) 也用于子元素。

 div {
  width: 100%;
  height: 200px;
  position: relative;
  background: blue;
}

text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: orange;
}
 <div>
   <text>Centered horizontally and vertically</text>
</div>

第三个选项,为了使元素垂直居中,使用 line-height 等于父元素的 height

 div {
  width: 100%;
  height: 200px;
  position: relative;
  background: blue;
}

text {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  line-height: 200px;
  background: orange;
}
 <div>
   <text>Centered horizontally and vertically</text>
</div>

原文由 user2230470 发布,翻译遵循 CC BY-SA 3.0 许可协议

这应该可以解决问题。

要清理您的 HTML,请像这样设置它并删除标签,例如 <center><font>

 <div class="Header" id="myHeader">
    <a class = "headerLogo">
        <h1>Lunation Boards</h1>
    </a>
</div>

您可以使用 display: flex 将标题居中:

 .Header {
    z-index: 100;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: #000000;
    height: 70px;
    display: flex;
    justify-content: center;
}

a {
  width: 100%;
}

h1 {
  margin: 0;
  color: #fff;
}

@media (max-width: 960px){
.Header .headerLogo {
    display: inline-block;
    width: 86px;
    height: 15px;
    margin-left: 6px;
}
}

这是更改的完整小提琴:

https://jsfiddle.net/xqamjrvr/

原文由 Cassidy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题