如何在 CSS 中垂直和水平居中方形 SVG,以便无论尺寸如何,只有图像在视口中可见
How to vertically and horizontally center a square SVG in CSS such that only the image is visible in the viewport no matter it dimensions
我正在尝试获取 SVG 并将其显示在移动和桌面浏览器上。 SVG 是 square,所以如果我尝试使用 contain
将它垂直和水平居中,它将在中心显示正方形图像。这不是我想要的。
我想要的是让它以图像为中心,然后放大,这样你看到的只是图像的部分图像和其余部分被视口裁剪。我无法上传图片给你看,但这张图应该有助于澄清。
手机:
┌┄┄┄┄╔═══════╗┄┄┄┄┐
┆ ║ ║ ┆
┆ ║ ║ ┆
┆ ║ ║ ┆
┆ ║ ║ ┆
┆ ║ ║ ┆
┆ ║ ║ ┆
└┄┄┄┄╚═══════╝┄┄┄┄┘
^ ^
| |
viewport image
桌面:
image
|
v
┌┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┐
╔═════════════════╗
║ ║
║ ║
║ ║
║ ║<-- viewport
║ ║
║ ║
╚═════════════════╝
└┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
我试过 object-fit: cover
但不行。
yourSelector {
background: url('path/to/your/svg') center /cover;
}
...应该这样做。
在上面的shorthand中,/cover
是
的缩写
background-size: cover;
看到它工作:
div {
background: url('https://placeholder.pics/svg/300') center /cover;
}
.one{
height: 200px;
width: 50%;
}
.two {
height: 100px;
width: 100%;
}
.three {
height: 400px;
width: 100px;
}
.four {
height: 200px;
width: 200px;
}
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
或 background-image
或 <body>
:
body {
background: url('https://placeholder.pics/svg/300') center /cover;
margin: 0;
min-height: 100vh;
}
我正在尝试获取 SVG 并将其显示在移动和桌面浏览器上。 SVG 是 square,所以如果我尝试使用 contain
将它垂直和水平居中,它将在中心显示正方形图像。这不是我想要的。
我想要的是让它以图像为中心,然后放大,这样你看到的只是图像的部分图像和其余部分被视口裁剪。我无法上传图片给你看,但这张图应该有助于澄清。
手机:
┌┄┄┄┄╔═══════╗┄┄┄┄┐
┆ ║ ║ ┆
┆ ║ ║ ┆
┆ ║ ║ ┆
┆ ║ ║ ┆
┆ ║ ║ ┆
┆ ║ ║ ┆
└┄┄┄┄╚═══════╝┄┄┄┄┘
^ ^
| |
viewport image
桌面:
image
|
v
┌┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┐
╔═════════════════╗
║ ║
║ ║
║ ║
║ ║<-- viewport
║ ║
║ ║
╚═════════════════╝
└┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
我试过 object-fit: cover
但不行。
yourSelector {
background: url('path/to/your/svg') center /cover;
}
...应该这样做。
在上面的shorthand中,/cover
是
background-size: cover;
看到它工作:
div {
background: url('https://placeholder.pics/svg/300') center /cover;
}
.one{
height: 200px;
width: 50%;
}
.two {
height: 100px;
width: 100%;
}
.three {
height: 400px;
width: 100px;
}
.four {
height: 200px;
width: 200px;
}
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
或 background-image
或 <body>
:
body {
background: url('https://placeholder.pics/svg/300') center /cover;
margin: 0;
min-height: 100vh;
}