在屏幕上定位一系列标签



我的 React Web 应用程序中有以下函数:

function DisplayInfo(props) {
    const flexStyle = {
        position: 'absolute',
        zIndex: 1,
        margin: 20,
        justifyContent: 'space-between',
        alignItems: 'center'
    };
    const labelStyle = {        
        zIndex: 1,
        margin: 20
    };
    return (      
        <div className="flex-container" style={flexStyle}>
            <label style={labelStyle}>
                Data1: {props.data}
            </label>
            <label style={labelStyle}>
                {props.moreInfo}
            </label>
            <label style={labelStyle}>
                {props.interestingMessage}
            </label>
        </div>  
    );
}

的目标是在屏幕上获得一个水平的、均匀分布的列表;但是,我刚刚将所有内容都放在屏幕的左上角。 我已经尝试过justifyContent: 'center'但如果没有区别。

请问有人可以让我走上正确的 css 路径吗?

为了使 justifyContent 属性正常工作,首先需要设置使其成为 flex 容器。此外,要使您的项目均匀分布,而不是 space-between ,请使用以下命令:

const flexStyle = {
    display: 'flex',
    position: 'absolute',
    zIndex: 1,
    margin: 20,
    justifyContent: 'space-evenly',
    alignItems: 'center'
};

除了上述内容之外,我注意到容器是绝对定位的。添加width 100%将为您解决问题。

这与 react 无关,您需要指定 absolute 元素的width

.flex-container {
  display: flex;
  position: absolute;
  z-index: 1; 
  width: 100%;
  justify-content: space-between;
  align-items: center
}
.labelStyle {
  padding: .5em 1em;
  background-color: yellow;
}
<div class="flex-container">
  <label class="labelStyle">
                data
            </label>
  <label class="labelStyle">
                moreInfo
            </label>
  <label class="labelStyle">
                interestingMessage
            </label>
</div>

最新更新