我一直在努力解决这个问题。我想学习的是了解使用语义 HTML 将元素垂直居中于导航的不同方法。我希望我的标志在左边,导航在右边。
我试图在我的导航元素上使用浮动,但徽标会损坏并且不会垂直居中。我为此使用了 clearfix,但我仍然找不到将徽标和导航垂直居中的方法。
请你帮帮我好吗?请解释你的答案?那么如果可能的话,您能否使用我的 html 的确切格式向我展示其他垂直居中徽标(左)和导航(右)的方法?
这是我的代码:https : //codepen.io/yortz/pen/pQdKWd
HTML
<!-- HEADER -->
<header>
<!-- LOGO -->
<a href="#"><img id="site-logo" src="http://lorempixel.com/190/25/" alt="Bookworm"></a>
<nav>
<ul class="clearfix">
<li><a href="#">About</a></li>
<li><a href="#">Articles</a></li>
<li><a href="#">News</a></li>
<li><a href="#">Get in Touch</a></li>
</ul>
</nav>
</header>
CSS
* {
box-sizing: border-box;
}
/* HIGHLIGHTING NAVIGATION ELEMENTS */
header {
background-color: #ccc;
}
nav {
background-color: aqua;
}
/* CENTERING NAVIGATION */
header {
width: 100%;
}
#site-logo,
nav {
display: inline-block;
vertical-align: middle;
}
nav ul {
list-style-type: none;
padding-left: 0;
}
nav ul li {
display: inline-block;
}
nav ul li a {
border: 1px solid red;
padding: 10px 15px;
display: block;
text-decoration: none;
}
nav ul li a:hover {
background-color: red;
color: #fff;
}
/* CLEAR FLOATS */
.clearfix::after {
content: "";
display: table;
clear: both;
}
请帮忙。谢谢!
我会使用 flexbox 在导航中定位
header {
display: flex;
justify-content: space-between; // pushes the logo to the left and the nav to the right
align-items: center; // center aligns children of nav vertically
}
如果你想在不使用 flexbox 的情况下实现类似的东西,你可以绝对定位标志:
header {
position: relative; // with this all children can be positioned absolutely, relative to the header
text-align: right; // this aligns the nav to the right of the header
}
header > a {
position: absolute; // positions the logo absolute, relative to header
top: 50%; // aligns the logo in the middle of the relative parent
left: 0; // aligns the logo to the left edge of the relative parent
transform: translateY(-50%); // changes the coordinates of the logo, to center it vertically (y-axis)
}
nav {
text-align: left; // just used to reset the text-alignment in the nav elements
}
我会考虑使用类而不是选择 a 标签,例如<a class="logo" href="...">...</a>
,然后header .logo {...}
在 CSS 中,而不是header > a {}
. 如果您向标题添加更多元素,那将更具未来证明。
快速提示:如果徽标高于导航,如果会溢出父容器,那么您需要修改父容器的高度来解决这个问题。如果您可以保证导航始终高于徽标,这对您来说不是问题,您可以保持标题的高度不变。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句