html - 中心(宽)SVG 元素在(较小)容器内,同时保持原始 SVG 宽度
问题描述
问题:
无法将宽 svg 居中(同时保留其原始宽度和高度)在“不宽”容器中。
脚步:
我设计了一个 SVG 元素,该元素具有3000px
我想要保留的默认宽度(我不希望它缩放或用于width=100%
缩小或扩展 SVG)。
我想将 SVG 元素放在一个具有width="100%"
固定高度的容器中,比如说250px
. 我正在尝试使 SVG 居中,例如如果我的屏幕只是1280px
宽的,则 svg 的第一部分(也是最后一部分)860px
将不可见。
*计算:(3000-1280)/2 = 860 *
关于如何实现这一目标的任何想法或帮助?我尝试使用变换/翻译将 SVG 移动到容器内,但没有积极的结果......
我越来越绝望了:(
代码:
(编辑以包括原始样式组件实现)
import React from 'react'
import styled from 'styled-components'
// Using styled-components
const Container = styled.div`
display: flex;
position: absolute;
left: 0;
right: 0;
width: 100%;
height: 250px;
text-align: center;
margin: 0 auto;
svg {
opacity:1;
margin: 0 auto;
position: absolute;
bottom: 0;
}
`;
class App extends React.Component {
render(){
return <Container>
<svg xmlns="http://www.w3.org/2000/svg" width="3000" height="250" viewBox="0 0 3000 250">
<path
id="Path_19510"
data-name="Path 19510"
d="M3000,477s-200,5-356,115-336,106-423,65c-42.736-20.14-85.29-30.391-117.537-35.613-39.32-8.192-83.3-7.111-121.162,1.629-100.53,23.2-271.333,200.166-392.685,78.826-108.44-108.422-192.276-65.146-231.863-79.47-51.647-18.685-39.84-75.2-109.955-102.123-44.932-17.247-111.989,2.153-169.479,21.616l-.028.01h0c-31.022,10.5-59.25,21.016-79.711,25.8a266.054,266.054,0,0,1-47.2,4q-6.693-.333-13.233-1.2C886.09,560.723,855.088,493.629,802,474c-119-44-240,40-425,128C199.67,686.351,0,463,0,463V768l1168.438-.005L2140,768h860Z"
transform="translate(0 -461.932)"
fill="#000"
/>
</svg>
</Container>
}
}
视觉预期结果:
解决方案
您需要做的就是将以下内容添加到 SVG。
<svg ... preserveAspectRatio="xMidYMid slice">
...etc...
</svg>
推荐阅读
- javascript - Campaign Monitor Ajax 表单提交
- firebase - 允许经过身份验证的用户创建文档的 Firestore 规则不起作用
- javascript - 如何为图表 js 数据标签插件格式化程序创建变量
- c# - C# | 如何在 Web 浏览器中选择下拉选项?
- java - 在 Azure VM 上使用 NGINX 对其他 Azure VM 进行负载平衡
- android - 从 Google Play 安装但从 Android Studio 安装时应用程序崩溃
- reactjs - 存储数据时出错,{}- Redux Persist
- unity3d - 如何使我的攻击组合系统更加模块化?
- apache-kafka - 卡夫卡镜子制造者的烦恼
- java - 如何使用 Google Cloud SDK 以编程方式更改活动项目