问题描述
移动端文字小于 12px会出现上偏移问题,通过各种方法table布局虽然能居中,但是会脱离文档流,其他布局错位。transform scale 缩放空间不会缩放。最终使用 zoom 缩放。
思路
虽然文字居中有问题,但是div居中没问题,所以对div居中。 使用三层 div 包裹文字, 最外层设position: relative; display: inline-block; 中间一层设display: flex; 最内层使用 zoom 缩放。 一像素边框用div设 position: absolute; 然后 transform: scale(0.5); 缩放。
代码
css
.center-text__wrapper {
position: relative;
box-sizing: border-box;
display: inline-block;
margin-right: 10px;
// height: 50px;
padding: 0 10px;
margin-bottom: 10px;
}
.center-text__wrapper-box {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.center-text__content {
color: black;
zoom: 0.5;
}
.center-text__wrapper-after {
// content: '';
position: absolute;
top: 0;
left: 0;
width: 200%;
height: 200%;
transform: scale(0.5);
transform-origin: 0 0;
border: 1px solid red;
border-radius: 15px;
}
jsx
import './index.less';
import { px2vw } from './util';
import React from 'react';
function CenterText(props) {
const { children, className, fontSize = 48, height = 50,
backgroundColor = 'transparent', borderRadius = 0, borderColor,
borderWidth = 1, borderStyle = 'solid', color, fontWeight = 'normal',
} = props;
const text = props.text || children[0];
return (
<>
<div className={`center-text__wrapper ${className}`} style={{ backgroundColor, height: px2vw(height) }}>
<div className="center-text__wrapper-box">
<div className="center-text__content" style={{ fontSize: px2vw(fontSize, 2), color, fontWeight }}>
{text}
</div>
</div>
<div className="center-text__wrapper-after" style={{ borderRadius: px2vw(borderRadius, 2), borderColor, borderWidth: px2vw(borderWidth, 2), borderStyle }} />
</div>
</>
);
}
export default CenterText;
util.js
export function px2vw(px, multiple) {
if (!px) return '0';
const val = parseFloat(px.toString() || '0');
if (multiple) {
return isNaN(val) ? '0' : `${Number((val / 7.5 * multiple).toFixed(3))}vw`;
} else {
return isNaN(val) ? '0' : `${Number((val / 7.5).toFixed(3))}vw`;
}
}
使用
{
new Array(100).fill('1').map(() => {
return (<CenterText className="conten-text-wrapper" text="abcdefg123456789" fontSize="22" height="44" borderRadius="12" color="#239466" fontWeight="700" >
aaa
</CenterText>);
})
}