如何在 React 应用程序中将 <div> 中的项目与 CSS 中的项目对齐?

How can I align items in <div> with CSS in a React app?

页面的设计勉强是这样的:

我想把 Redbox(里面有 1 个)放在 "PlayerOneDiv".

中间

"PlayerTwoDiv".

的黄色框也是如此
return (<div className="App">
        <div className="sampleDiv" onClick={getData}>
            <div className="playerOneScoreDiv">1</div>
            <div className="midDiv">
                <Box param={pitValue1} funcParam={getData}> b</Box>
            </div>
            <div className="playerTwoScoreDiv">3</div>
        </div>

PlayerOneDiv和外div的样式是:

  .sampleDiv {
    background-color: green;
    margin: auto;
    width: 60%;
    padding: 100px;
    border-radius: 14px;
    display: flex;
    flex-direction: row;
}

.playerOneScoreDiv {
    width: 15%;
    height: 96px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 3rem;
    font-weight: bold;
    border-radius: 14px;
    color: #fff;
    margin-right: 4px;
    margin-bottom: 4px;
    cursor: default;
    background-color: red;
}

当我玩 PlayerOneDiv 时,数字“1”在盒子里移动,但我无法将盒子本身移动到 div 的中间。

我需要更改哪个 属性 或者我是否需要添加另一个包装器 div?

HTML:

<div id="container">
  <div id="left">
    
  </div>
  <div id="middle">
    
  </div>
  <div id="right">
    
  </div>
</div>

CSS:

#container {
  width: 220px;
  height: 32px;
  background-color: khaki;
  overflow-x: clip;
  display: flex;
}

#left {
  justify-content: left;
  width: 32px;
  float: left;
  height: 32px;
  line-height: 32px;
  background-color: darkkhaki;
}

#middle {
  width: 32px;
  height: 32px;
  margin: 0 auto;
  background-color: darkkhaki;
}

#right {
  width: 32px;
  height: 32px;
  float: right;
  background-color: darkkhaki;
}

下面是示例代码,可以让您了解您的案例。

.sampleDiv{
  display: flex;
  gap:10px;
  justify-content: space-around;
}
.playerOneScoreDiv,
.playerTwoScoreDiv{
  background: red;
  flex-basis: 25%;
  display: flex;
  align-self: center;
  justify-content: center;
}
.midDiv{
  background: green;
  flex-basis: 50%;
}
<div class="sampleDiv">
    <div class="playerOneScoreDiv">1</div>
    <div class="midDiv">
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
    </div>
    <div class="playerTwoScoreDiv">3</div>
</div>

让我简要解释一下这段代码:

  • 我已将 parent div sampleDiv 设为 flex,您可能正在寻找的主要内容是 justify-content: space-around。要了解更多关于 justify-content,您可以访问 justify-content
  • 虽然第一种情况应该可以满足您的需求,如果您想要更多控制和切换每个 child div 的位置,您可以设置此 child div 作为一个新的 flex 也是如此。如果您添加 属性 align-selfalign-self:center,它会尝试将自己与横轴对齐。对于 align-self 上的所有可用选项,您会看到 align-self
  • gap 将在每个 flex-item
  • 之间增加间隙
  • flex-basis 将设置 flex-item
  • 的大小