根据外部导航将h1居中

时间:2019-06-11 23:39:20

标签: html css

我的导航栏中有一个h1,当前基于h1的宽度居中。我将如何使用text-align来使标题基于nav的宽度居中?

这是我的HTML和CSS:

* {
  margin: 0;
  padding: 0;
  font-family: "Big Caslon","Book Antiqua","Palatino Linotype",Georgia,serif;
}

h1 a {
  text-decoration: none;
  color: inherit;
}

.logo {
  height: 100%;
}

nav {
  width: 100%;
  height: 90px;
  background-color: black;
  display: flex;
 
}

nav h1 {

text-align: center;
margin: 15px 0;
  color: white;
  font-size: 44px;
  line-height: 55px;

  flex: 1 0 auto;


}
<nav>
    <img class="logo" src="https://www.brachaprinting.com/wp-content/uploads/2013/10/Apple-logo1.jpg">
    <h1> <a href="index.html"> The Novel Column </a> </h1>
</nav>

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以将导航设置为position的{​​{1}},这意味着relative内部的任何元素都将在此元素的范围内。然后将h1设置为absolute的{​​{1}},这将从页面的常规流中删除该元素,并使它与父元素以及{{1}的position一起流动}。在此处,您可以使用absolutepositionrelative将其居中,这将使margin: 15px auto;元素的导航宽度为100%,从而正确地将其居中。

left: 0
right: 0

现在此方法也有其后备之处,您将无法单击徽标,但是可以通过设置h1* { font-family: "Big Caslon","Book Antiqua","Palatino Linotype",Georgia,serif; margin: 0; padding: 0; } h1 a { color: inherit; text-decoration: none; } .logo { height: 100%; } nav { background-color: black; display: flex; height: 90px; position: relative; width: 100%; } nav h1 { color: white; flex: 1 0 auto; font-size: 44px; left: 0; line-height: 55px; margin: 15px auto; position: absolute; right: 0; text-align: center; }的位置来解决此问题,因此徽标元素会更高比<nav> <img class="logo" src="https://www.brachaprinting.com/wp-content/uploads/2013/10/Apple-logo1.jpg"> <h1> <a href="index.html"> The Novel Column </a> </h1> </nav>更具可点击性。

答案 1 :(得分:0)

Flexbox是一种完美的方法,而您已经快要在那里了。

我添加了一个类为.ghost的空div来平衡徽标。由于我知道徽标的宽度为90px,因此我将ghost div设置为相同,并且div和徽标都获得相似的flex设置:

.logo {
  height: auto;
  width: 90px;
  flex: 0 0 90px; // same
}
.ghost {
  width: 90px;
  flex: 0 0 90px; // same
}

现在,在允许<h1>增长(flex: 1 0 auto)的情况下,由于位于右侧的幽灵div,它将自然占据所有剩余空间并保持完美居中。

>

* {
  margin: 0;
  padding: 0;
  font-family: "Big Caslon", "Book Antiqua", "Palatino Linotype", Georgia, serif;
}

h1 a {
  text-decoration: none;
  color: inherit;
}

.logo {
  height: auto;
  width: 90px;
  flex: 0 0 90px;
}

nav {
  width: 100%;
  height: 90px;
  background-color: black;
  display: flex;
}

nav h1 {
  text-align: center;
  margin: 15px 0;
  color: white;
  font-size: 44px;
  line-height: 55px;
  flex: 1 0 auto;
}

.ghost {
  width: 90px;
  flex: 0 0 90px;
}
<nav>
  <img class="logo" src="https://www.brachaprinting.com/wp-content/uploads/2013/10/Apple-logo1.jpg">
  <h1><a href="index.html">The Novel Column</a></h1>
  <div class="ghost"><!-- nothing here --></div>
</nav>