英文:
Safari not displaying SVG in the right position
问题
我想创建一些图像占位符,停留1秒,然后淡出显示图像。我使用通过读取图像宽度和高度生成的SVG。
这些图像(和SVG)是响应式的,会适应容器的大小。
我还想随机将图像放置在容器内的四个不同位置:右侧,左侧(纵向),顶部,底部(横向)。
在Chrome上,SVG被放置在图像的正上方,而在Safari上,SVG内的<rect>始终居中。
以下是代码的一部分:
<div class="container position-top">
<svg viewBox="0 0 63.863757317722 100" xmlns="http://www.w3.org/2000/svg">
<rect width="1200" height="1879"></rect>
</svg>
<img src="image.jpg" alt="">
</div>
这是一个CodePen示例链接:
https://codepen.io/bbbellon/pen/PoxYQpP
英文:
I want to create some image placeholders that stay for 1 second and then fade out displaying the image. I am using SVGs that I generate by reading the image width and height.
The images (and SVGs) are responsive, adapting to the container size.
I want to also randomly place the images on four potential different places within the container: right, left (for portrait) and top, bottom (for landscape).
The SVGs are placed right on top of the images on Chrome, while on Safari the <rect> inside of the SVG is always centered.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container {
width: 100%;
height: 100%;
display: flex;
position: relative;
}
.container img {
max-width: 100%;
max-height: 100%;
}
.continer svg {
max-width: 100%;
max-height: 100%;
position: absolute;
}
.container svg rect {
width: 100%;
height: 100%;
}
<!-- language: lang-html -->
<div class="container position-top">
<svg viewBox="0 0 63.863757317722 100" xmlns="http://www.w3.org/2000/svg">
<rect width="1200" height="1879"></rect>
</svg>
<img src="image.jpg" alt="">
</div>
<!-- end snippet -->
Here is a codepen:
https://codepen.io/bbbellon/pen/PoxYQpP
答案1
得分: 1
在 .container svg
中,您需要将以下内容更改:
max-width: 100%;
max-height: 100%;
更改为:
width: auto;
height: 100%;
设置 max-height
和/或 max-width
不是问题,但它不会告诉 <svg>
您实际希望它的大小是多少。如果您使用开发工具查看原始代码,您会看到 <svg>
占据整个 .container
,而 <rect>
位于其中央。将 <svg>
的高度设置为父元素的100%,然后将宽度设置为 auto
,viewBox
属性会自动管理 <svg>
的缩放。
另外,您不需要在 .container svg rect
中添加以下内容:
width: 100%;
height: 100%;
英文:
On .container svg
you need to switch
max-width: 100%;
max-height: 100%;
to be
width: auto;
height: 100%;
Setting a max-height
and / or max-width
is not a problem but it does not tell the <svg>
what size you actually want it to be. If you use dev tools you'll see, with your original code, the <svg>
takes up the whole .container
and the <rect>
sits centrally within that. The placement of the <rect>
within the <svg>
is expected behaviour. If you tell the <svg>
to take up 100% of its parent's height and then set the width to auto
the viewBox
attribute will manage the scaling of the <svg>
on your behalf.
As a side note, you do not need the following on .container svg rect
width: 100%;
height: 100%;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论