React中SVG Logo尺寸与左外边距无法修改问题求助
问题描述
我尝试为SVG格式的Logo设置50px左外边距并放大它,但无论修改代码中的相关样式,都无法改变该图片的尺寸与外边距。
参考效果
- Figma设计示例:Logo带有50px左外边距,尺寸符合设计要求
- 当前网站实际效果:Logo没有左外边距,尺寸未达到设计预期
Header组件代码(header.jsx)
import React, { useState, useContext, useEffect } from 'react'; import { useCookies } from 'react-cookie'; import { useNavigate } from 'react-router'; import { useDispatch, useSelector } from 'react-redux'; import Modal from 'react-modal'; import { useGoogleLogin, useGoogleLogout } from 'react-google-login'; import ShortID from 'shortid'; import { setIsLoggedIn } from '../../../redux/actions/pagebuilder'; import { AuthContext } from '../../../components/AuthContext/AuthContext'; import * as S from './Header.style'; import { customStyles } from './Header.style'; import { apiDomain, fp } from '../../../config'; import Link from '../../../components/Link'; import UserLogin from '../../../components/UserLogin'; import RegisterModal from '../../../components/RegisterModal'; import LogoImg from '../../../assets/images/logologo.png'; const navLinks = [ { text: 'Learning', to: '/learning-center', color: 'primary', }, { text: 'About', to: '/about', color: 'primary', }, { text: 'Contact', to: '/contact', color: 'primary', }, ]; function Header() { const [user, setUser] = useContext(AuthContext); const [modalIsOpen, setIsOpen] = useState(false); const [loginModalIsOpen, setLoginModalIsOpen] = useState(false); const [companyHash, setCompanyHash] = useState(''); // eslint-disable-next-line no-unused-vars const [cookies, setCookie, removeCookie] = useCookies(['atomic_session']); // stored cookie hash and expiration date let cookieHash = ''; // eslint-disable-next-line no-unused-vars const [cookieExpirationDate, setCookieExpirationDate] = useState( new Date(new Date().setFullYear(new Date().getFullYear() + 2)), ); const dispatch = useDispatch(); const navigate = useNavigate(); // Bind modal to the appElement Modal.setAppElement('#root'); function googleLoginApiResponseHandler(response) { if (response === 'USER_NOT_FOUND') { console.log('Not yet registered.'); } else { console.log('Login Successful'); console.log(response.USER_SESSION_HASH); cookieHash = response.USER_SESSION_HASH; setCookie('atomic_session', cookieHash, { path: '/', expires: cookieExpirationDate, sameSite: 'Strict', }); // We are TEMPORARILY setting isAuth to false, which is NOT normal, for the developers to have faster access to the projects page during the development. This must be turned back to true before the deployment. setUser((prevState) => ({ ...prevState, isAuth: true })); dispatch(setIsLoggedIn(true)); } } const onSuccess = (res) => { const requestOptions = { method: 'POST', mode: 'cors', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: JSON.stringify({ command: 'login_with_google', fp, email: res.profileObj.email, access_token: res.accessToken, }), }; fetch(`${apiDomain}/user.php`, requestOptions) .then((response) => response.json()) .then((data) => googleLoginApiResponseHandler(data)) .catch((error) => { console.error(error); }); }; const onLogoutSuccess = (res) => { dispatch(setIsLoggedIn(false)); setUser((prevState) => ({ ...prevState, isAuth: false })); }; const onFailure = (res) => { if (res) { console.log(res); } return null; }; const { signIn } = useGoogleLogin({ onSuccess, onFailure, clientId: '523964094560-utcl46ugtmcl8p3nfi7s68bc7pplcio4.apps.googleusercontent.com', cookiePolicy: 'single_host_origin', isSignedIn: true, }); const { signOut } = useGoogleLogout({ onLogoutSuccess, onFailure, clientId: '523964094560-utcl46ugtmcl8p3nfi7s68bc7pplcio4.apps.googleusercontent.com', cookiePolicy: 'single_host_origin', }); const logout = () => { removeCookie('atomic_session'); localStorage.removeItem('token'); setUser((prevState) => ({ ...prevState, isAuth: false })); signOut(); }; function openLoginModal() { setLoginModalIsOpen(true); } function closeLoginModal() { setLoginModalIsOpen(false); } useEffect(() => { if (user.isAuth === true) { navigate('/projects-main/all-projects'); } }, [user, cookies]); useEffect(() => { signIn(); const { search } = window.location; const params = new URLSearchParams(search); const registration = params.get('registration'); if (registration) { setIsOpen(true); setCompanyHash(registration); } }, []); return ( <S.HeaderWrapper> <Link to={user.isAuth ? '/projects-main/all-projects' : '/'}> <S.Logo src={LogoImg} alt="Logo" /> </Link> <S.NavBar> {navLinks.map((link) => ( <Link key={ShortID.generate()} to={link.to} color={link.color}> {link.text} </Link> ))} {user.isAuth ? ( <S.NavButton color="primary" onClick={() => logout()}> Logout </S.NavButton> ) : ( <S.NavButton color="primary" onClick={openLoginModal}> Login </S.NavButton> )} <S.NavButton color="primary" onClick={() => { setIsOpen(true); }} > Register </S.NavButton> <Modal isOpen={modalIsOpen} onRequestClose={() => { setIsOpen(false); }} style={customStyles} > <RegisterModal companyHash={companyHash} /> </Modal> </S.NavBar> <UserLogin isOpen={loginModalIsOpen} close={closeLoginModal} /> </S.HeaderWrapper> ); } export default Header;
样式代码(header.style.js)
import styled from 'styled-components'; import LinkButton from '../../../components/LinkButton'; import { theme } from '../../../styles/theme'; export const HeaderWrapper = styled.header` box-sizing: border-box; align-items: center; display: flex; justify-content: space-between; height: 71.5px; width: 100%; margin-bottom: 100px; padding: 80px 38px 0 50px; margin-left: 50px; `; export const Logo = styled.img` height: 73px; width: 200px; margin-left: 100px; margin-top: 10px; `; export const NavBar = styled.nav` display: flex; padding-top: 5px; a { margin-left: 57px; text-transform: uppercase; font-size: 14px; font-family: ${({ theme }) => theme.font.font3.new}; font-weight: ${({ theme }) => theme.fontWeight.med_700}; } a:first-of-type { margin-left: 0px; } `; export const NavButton = styled(LinkButton)` margin-left: 52px; text-transform: uppercase; font-size: 14px; font-family: ${({ theme }) => theme.font.font3.new}; font-weight: ${({ theme }) => theme.fontWeight.med_700}; `; export const customStyles = { overlay: { backgroundColor: 'rgba(30, 30, 30, .9)', }, content: { position: 'absolute', width: '460px', height: '718px', top: '50%', left: '50%', background: '#111', border: `4px solid ${theme.colors.modal.border}`, borderRadius: '15px', boxSizing: 'border-box', transform: 'translate(-50%, -50%)', }, };
解决方案
确认Logo资源类型:代码中导入的是
logologo.png,但描述里说是SVG,先核实实际使用的文件类型。如果是PNG,确保图片本身没有尺寸限制;如果是SVG,建议直接导入为React组件,样式控制更灵活。提升样式优先级:当前
Logo样式可能被父组件或全局样式覆盖,可临时添加!important排查(不推荐长期使用),或优化选择器:
export const Logo = styled.img` height: 73px !important; width: 200px !important; margin-left: 50px !important; margin-top: 10px; `;
- 检查父容器约束:
HeaderWrapper同时设置了margin-left:50px和padding-left:50px,可能干扰Logo的外边距计算。可以:- 移除
HeaderWrapper的margin-left和padding-left,将左间距完全交给Logo的margin-left - 给Logo的父元素
Link添加块级样式,确保支持margin:
- 移除
// 在Header.style.js中新增 export const LogoLink = styled(Link)` display: inline-block; `; // 在header.jsx中替换原Link <S.LogoLink to={user.isAuth ? '/projects-main/all-projects' : '/'}> <S.Logo src={LogoImg} alt="Logo" /> </S.LogoLink>
- SVG专属处理:如果是SVG文件,改用
ReactComponent导入,直接控制尺寸和样式:
// 导入方式修改 import { ReactComponent as LogoImg } from '../../../assets/images/logologo.svg'; // 使用组件 <S.Logo as={LogoImg} alt="Logo" /> // 样式调整 export const Logo = styled.svg` height: 73px; width: 200px; margin-left: 50px; `;
- 浏览器调试定位:打开开发者工具(F12),选中Logo元素,查看
Styles面板中被划掉的样式,针对性调整选择器优先级。
内容的提问来源于stack exchange,提问作者Alphasigma1436
相关产品推荐
相关产品推荐

