如何解决将行头中的行内块元素垂直居中
在页眉顶部横幅中:
#header { background-color: #eaeaea; }
#header a { display: inline-block; margin-right: 1.5em; }
.logo { margin-right: 6em; }
<div id="header">
<img src="https://via.placeholder.com/150x120" class="logo">
<a href="">Lorem</a>
<a href="">Ipsum</a>
<a href="">Contact</a>
</div>
如今,将3个右链接垂直放置在横幅内的主要方法是什么?
我知道如何使用position: relative; top:-...px
或类似的方法甚至是<table>
来做到这一点,但是如今,什么被认为是最合适的方法,尤其是对于响应式设计?
您会为此使用flex
功能吗?如果可以,怎么办?
我还希望将3个链接的组粘贴到屏幕的右边框,这样,如果我们调整浏览器宽度的大小,它将始终沿右边框浮动。我本打算使用float: right
,但可能有比混合flex
和float
更好的解决方案?
PS:最后的详细信息不在链接的问题Flexbox: center horizontally and vertically和How to Vertical align elements in a div?中,因此不是重复的内容。
解决方法
我愿意将{strong> flex 与align-items:center
配合使用,以进行响应式设计。
请参见下面的代码:
#header{
background-color: #eaeaea;
display:flex;
align-items:center;
justify-content:space-between;
}
#header a{
display: inline-block;
margin-right: 1.5em;
}
.logo{
margin-right: 6em;
}
<div id="header">
<img src="https://via.placeholder.com/150x120" class="logo">
<div id="links">
<a href="">Lorem</a>
<a href="">Ipsum</a>
<a href="">Contact</a>
</div>
</div>
,
当涉及文本和项目的垂直居中时,此技巧很方便:
#header {
display: flex;
align-items: center;
}
一种更可靠(复杂的)方法是使用网格包装器
.center {
display: grid;
grid-template-areas: 'a b c';
grid-template-rows: 1fr max-content 1fr;
}
.center > * {
grid-area: b
}
<div id="header">
<img src="https://via.placeholder.com/150x120" class="logo">
<a class="center" href=""><span>Lorem</span></a>
<a class="center" href=""><span>Ipsum</span></a>
<a class="center" href=""><span>Contact</span></a>
</div>
,
如果您不关心旧的浏览器(IE),则可以使用place-items
代替align-items
。
#header{
background-color: #eaeaea;
display: flex;
place-items: center;
}
#header a{
display: inline-block;
margin-right: 1.5em;
}
.logo{
margin-right: 6em;
}
<div id="header">
<img src="https://via.placeholder.com/150x120" class="logo">
<a href="">Lorem</a>
<a href="">Ipsum</a>
<a href="">Contact</a>
</div>
引用https://developer.mozilla.org/en-US/docs/Web/CSS/place-items:
CSS place-items的简写属性允许您在诸如Grid或Flexbox之类的相关布局系统中同时沿块和内联方向对齐项目(即align-items和justify-items属性)。如果未设置第二个值,则第一个值也将被使用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。