react 等比例容器
利用margin 100%去实现比例容器也可使用padding,传入想要的宽高比后展现结果
实现
js
//等比例组件
export function EqualProportionSpan({ w, h, children }) {
const style = {
marginTop: w && h ? `${(h / w) * 100}%` : "100%"
}
return <div className="equal-proportion">
<div className="equal-proportion-body">
{
children
}
</div>
<div style={style} />
</div>
}
css
//兼容等比例
.equal-proportion {
position: relative;
overflow: hidden;
box-sizing: border-box;
}
.equal-proportion.equal-proportion-body {
position: absolute;
height: 100%;
width: 100%;
}
使用实例
function App(props) {
return <div style={{maxWidth:"500px",maxHeight:"500px"}}>
<EqualProportionSpan w={15} h={10}>
<div style={{width:"100%",height:"100%",backgroundColor:"red"}}>
</div>
</EqualProportionSpan>
</div>
}
效果如下