【发布时间】:2018-12-25 00:28:07
【问题描述】:
我有一个 Gatsby.js 网站,使用 gatsby-remark-images 来处理我的降价文章中的图像。
文章宽度固定,但图片两边溢出:
margin: 0 -15rem;
这适用于跨越整个宽度的大图像,但较小的图像不在父级中居中。
我喜欢使用 flexbox 解决方案,例如 this answer,但它不起作用,因为 gatsby-remark-images 依赖于 display: block; 正确定位 base64 占位符图像以及高分辨率图像。
当前生成的html是这样的:
<span class="gatsby-resp-image-wrapper">
<span class="gatsby-resp-image-background-image"> <!-- the base64 image is a background of this span -->
<img
class="gatsby-resp-image-image"
alt="My image"
src="/static/b07bc/my-image.jpg"
srcset="
/static/d942e/my-image.jpg 320w,
/static/c1221/my-image.jpg 640w,
/static/b07bc/my-image.jpg 1280w"
sizes="(max-width: 1280px) 100vw, 1280px"
>
</span>
</span>
还有样式:
.gatsby-resp-image-wrapper {
position: relative;
display: block; /* for base64 image placeholder */
margin: 0 -15rem; /* overflowing parent container */
max-width: 1280px;
}
.gatsby-resp-image-background-image { /* this is the base64 image */
padding-bottom: 75%;
position: relative;
bottom: 0;
left: 0;
background-image: url('data:image/jpeg;base64,/some/url/');
background-size: cover;
display: block;
}
.gatsby-resp-image-image {
width: 100%;
height: 100%;
margin: 0;
vertical-align: middle;
position: absolute;
top: 0;
left: 0;
}
如何将所有这些水平居中?
我认为有两种可能的方法来解决这个问题:
- 以
margin: 0 auto;居中图像并找到另一种方法使其溢出父级 - 找到一种在没有
margin和没有flexbox的情况下使图像居中的方法
有什么想法吗?
【问题讨论】:
-
这里您缺少点 .gatsby-resp-image-image 您是否尝试将 left:50% 添加到图像中
-
感谢@godfather,点是错字:) 左边距的问题是我应该将它添加到 base64 占位符图像(
<span>的背景和实际图像,它是<span>的子代。我想知道是否没有更简单、更清洁的解决方案