【发布时间】:2021-01-10 00:22:09
【问题描述】:
我在容器元素中有图像。当图像高度小于容器高度时,我希望图像位于容器顶部。当图像宽度小于容器宽度时,我希望图像居中。
这就是我希望它的外观,它适用于桌面 Firefox 和 Chrome。
但是,在桌面版 Safari 和移动版 Safari、Firefox 和 Chrome 上,它看起来像这样,较短的图像垂直居中,较窄的图像被拉伸以适应容器宽度:
#container {
display: flex;
flex-direction: row;
}
.mainImageContainer {
width: 500px;
height: 375px;
margin: 1rem;
}
.mainImageBtn {
background-color: rgb(231, 60, 60);
display: -webkit-box; /* tried this did not work */
display: -webkit-flex; /* tried this did not work */
display: -moz-box; /* tried this did not work */
display: -ms-flexbox; /* tried this did not work */
display: flex;
width: 500px;
height: 375px;
border: none;
padding: 0;
justify-content: center;
-webkit-box-pack: start; /* tried this did not work */
-webkit-box-align: start; /* tried this did not work */
-webkit-flex-align: start; /* tried this did not work */
-ms-flex-align: start; /* tried this did not work */
-webkit-align-items: start; /* tried this did not work */
align-items: flex-start;
}
.mainImage {
cursor: zoom-in;
max-width: 100%;
max-height: 100%;
}
<div id="container">
<div class="mainImageContainer">
<button class="mainImageBtn">
<img class="mainImage" src="https://eoja82.github.io/For-Sale/img/car_2.jpg" alt="car"></img>
</button>
</div>
<div class="mainImageContainer">
<button class="mainImageBtn">
<img class="mainImage" src="https://eoja82.github.io/For-Sale/img/tumbler%20-%202.jpeg" alt="instructions"></img>
</button>
</div>
</div>
我阅读了这篇文章,但没有一个解决方案适合我:How do I make flex box work in safari?。
我使用的是最新版本的浏览器。
【问题讨论】:
-
您能否添加几张实际图片来重现该问题?
-
我添加了图片。
-
是的,我看到了这个问题,我猜浏览器处理这部分的方式不同,但看起来问题是按钮标签哈哈
-
最初,我只有 img 标签,但我收到了来自 Gatsby 的关于具有点击事件的非交互式元素的可访问性警告,因此我将 img 包装在一个按钮中以消除警告。
-
您也可以使用锚元素并将其设为
role="button"和href=#。必须有 href 否则违反可访问性