在React应用中适配多端(移动端、PC端)时,使用px和rem单位进行布局是一种常见的做法。以下是一些使用px和rem相互转换的多场景详细使用案例:
1. 基础转换场景:将设计稿的px值转换为rem值。
案例:
/* 假设设计稿中的设计尺寸为375px宽,即iPhone 6的屏幕宽度 */ html { font-size: 16px; /* 1rem = 16px */ } .container { width: 23.4375rem; /* 375px / 16px */ margin: 0.625rem; /* 10px / 16px */ } 123456789 2. 响应式设计
场景:创建响应式布局,适配不同屏幕尺寸。
案例:
html { font-size: 16px; /* 默认字体大小 */ } @media (min-width: 768px) { html { font-size: 18px; /* PC端字体大小 */ } } /* 使用rem单位创建响应式宽度 */ .content { width: 90%; max-width: 60rem; /* 960px / 16px */ } 123456789101112131415 3. 组件级别的适配
场景:在React组件中使用px和rem进行布局。
案例:
import React from 'react'; import './Component.css'; const Component = () => { return ( <div className="component"> {/* 组件内容 */} </div> ); }; export default Component; 123456789101112
/* Component.css */ .component { padding: 20px; /* 20px / 16px */ font-size: 1rem; /* 16px */ } 12345 4. 使用CSS模块
场景:使用CSS模块管理样式,便于维护。
案例:
import React from 'react'; import styles from './Component.module.css'; const Component = () => { return ( <div className={styles.component}> {/* 组件内容 */} </div> ); }; export default Component; 123456789101112
/* Component.module.css */ .component { width: 23.4375rem; /* 375px / 16px */ padding: 1.25rem; /* 20px / 16px */ } 12345 5. 使用CSS-in-JS库
场景:使用CSS-in-JS库(如styled-components)进行样式编写。
案例:
import React from 'react'; import styled from 'styled-components'; const Container = styled.div` width: 23.4375rem; /* 375px / 16px */ margin: 0.625rem; /* 10px / 16px */ `; const Component = () => { return <Container>{/* 组件内容 */}</Container>; }; export default Component; 12345678910111213 6. 动态调整根元素字体大小
场景:根据屏幕宽度动态调整根元素字体大小。
案例:
import React, { useEffect } from 'react'; const App = () => { useEffect(() => { const handleResize = () => { const baseSize = 16; const scaleFactor = window.innerWidth / 375; // 以375px为基准宽度 document.documentElement.style.fontSize = `${baseSize * scaleFactor}px`; }; window.addEventListener('resize', handleResize); handleResize(); // 初始化时调用一次 return () => { window.removeEventListener('resize', handleResize); }; }, []); return ( <div>{/* 应用内容 */}</div> ); }; export default App;
123456789101112131415161718192021222324 注意事项 使用rem单位时,确保根元素的字体大小适当,以便在不同设备上保持一致性。在使用媒体查询进行响应式设计时,选择适当的断点。动态调整根元素字体大小时,注意性能影响,避免频繁触发重排。考虑使用CSS预处理器(如Sass或Less)来简化px和rem的转换。