首页 > 解决方案 > 如何在另一个 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 之上?

标签: javascriptcssreactjssassjsx

解决方案


将其放在单独的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;
}

推荐阅读