javascript - 如何在另一个 div 内动态改变宽度的 div 上居中文本?
问题描述
我正在 React 中为显示自动化结果的应用程序创建一个组件。我正在尝试创建一个显示通过测试百分比的自定义进度条。但是,当我尝试将文本居中时,它相对于内部 div 居中。
我的进度条的代码是:
import React from 'react';
import classes from './ProgressBar.modules.scss';
const progressBar = props => {
return (
<div className={ classes.ProgressBar }>
<div style={{ width: props.passed }}>
{ props.passed }
</div>
</div>
);
};
我的 SCSS 文件如下所示:
.ProgressBar {
width: 125px;
max-width: 125px;
background: rgb(255, 97, 97);
border-radius: 4px;
height: 40px;
box-shadow: 0 2px 3px rgb(110, 109, 109);
overflow: hidden;
transition: 0.2s ease-in-out;
}
.ProgressBar div {
background: rgb(98, 167, 98);
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
height: 40px;
padding: 8px 1px 9px 5px;
box-sizing: border-box;
font-weight: bold;
color: white;
}
我尝试使文本居中,但它仅相对于绿色保持居中。如何将其置于两个 div 之上?
解决方案
将其放在单独的span
(或div
, p
, 不管)中:
const progressBar = props => {
return (
<div className={ classes.ProgressBar }>
<div style={{ width: props.passed }}></div>
<span className="label">{props.passed}</span>
</div>
);
};
position: relative
在外容器上使用:
.ProgressBar {
position: relative; /* <<< */
width: 125px;
max-width: 125px;
background: rgb(255, 97, 97);
border-radius: 4px;
height: 40px;
box-shadow: 0 2px 3px rgb(110, 109, 109);
overflow: hidden;
transition: 0.2s ease-in-out;
}
然后为 设置样式span
,例如:
.ProgressBar .label {
position: absolute; /* <<< reason for relative positioning */
top: 0;
left: 0;
width: 100%;
padding: 5px; /* <<< adjust to your needs */
text-align: center;
}
推荐阅读
- spring - 为什么推荐spring bean的接口?
- angularjs - 使用 angularjs 登录到 Domino 服务器不返回 DomAuthSessId
- python - 通过使用另一个值列表中的值,询问用户要更新多少值并更新字典中的那么多值
- python - Sklearn 在线预测,batch vs one by one
- python - 如何在pyspark中重命名数据框的列名?
- telegram - 如何检查机器人网址是否仅在电报的应用浏览器中打开
- ios - 如何在 UITableViewCell 目标 c 中添加复选框按钮
- sql - 使用 ROWNUM Oracle 选择第 n 行
- apache-camel - 使用包含日期范围的 sql 的骆驼端点 URI
- php - Symfony - Doctrine Single Table Inheritance ManyToOne 与父实体的关联