【发布时间】:2021-10-09 00:13:19
【问题描述】:
在这个codepen中,我写了一个这样的flexbox导航栏:
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-color: #f9fafb;
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, sans-serif, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
line-height: 1.5;
}
nav {
background-color: #fff;
position: fixed;
left: 0;
right: 0;
top: 0;
width: 100%;
display: flex;
justify-content: space-between;
box-shadow: 0px 0px 10px 10px #ddd;
}
#items {
display: flex;
flex: 1 0 auto;
justify-content: space-evenly;
list-style-type: none;
padding: 32px;
}
#items>li {
display: flex;
justify-content: center;
align-items: center;
}
<nav>
<ul id='items'>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</nav>
请注意,此导航的高度为88px。
如果我将图像作为 flex 子元素添加到导航,它会将其父(导航栏)的总高度增加 4px(新高度:92px)。
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-color: #f9fafb;
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, sans-serif, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
line-height: 1.5;
}
nav {
background-color: #fff;
position: fixed;
left: 0;
right: 0;
top: 0;
width: 100%;
display: flex;
justify-content: space-between;
box-shadow: 0px 0px 10px 10px #ddd;
}
#logo {
display: flex;
flex: none;
justify-content: center;
}
#logo>img {
height: 100%;
width: auto;
object-fit: contain;
}
#items {
display: flex;
flex: 1 0 auto;
justify-content: space-evenly;
list-style-type: none;
padding: 32px;
}
#items>li {
display: flex;
justify-content: center;
align-items: center;
}
<nav>
<div id="logo">
<img src="https://upload.wikimedia.org/wikipedia/commons/2/2f/Google_2015_logo.svg" alt="Example logo" />
</div>
<ul id='items'>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</nav>
如何使图片(在本例中为 Google 徽标)适合 100% 的可用高度,同时
a)保持其纵横比
b) 不超过导航栏的高度(/增加它的高度来补偿)
谢谢!
【问题讨论】:
-
img { 高度:100%; }
-
指定导航元素的高度 (
88px)。 -
比例已知?
-
使用图片作为div的背景并应用
background-size: cover; -
我被分配了审查这个问题的任务,因为它是由一个新的贡献者撰写的,仅供参考,这是一个很好的问题,干得好。 +1向上+
标签: html css image svg flexbox