【问题标题】:Why does my display flexbox have empty white space on the right?为什么我的显示弹性框右侧有空白区域?
【发布时间】:2021-07-07 00:06:29
【问题描述】:

我正在制作一个在#bar-container 中显示 100 个随机高度的应用程序,它是一个 div。出于某种原因,我的应用程序在我的栏右侧有一些空白。我希望 div 缩小到内容的大小,然后在屏幕上居中。我的应用如下所示:

JSX:

    return (
    <div id="main-container">

        <button onClick={() => newArray()}>New Array</button>

        <div id="bar-container">

            {arr.map((value, index) => (
                <div
                    className='bar'
                    key={index}
                    style={{
                        backgroundColor: "lightgreen",
                        height: `${value}px`
                    }}
                >
                    {value}
                </div>
            ))}

        </div>
    </div>

CSS:

#bar-container {
    align-items: flex-end;
    display: flex;
    margin: 100px;
}

.bar {
    margin: 0 2px;
}

我尝试将 auto 包含在 #bar-container 的边距中,但它不会使条居中,也不会删除多余的空白。

【问题讨论】:

  • 尝试删除margin: 100px;

标签: html css flexbox jsx display


【解决方案1】:

使用justify-content 属性,

justify-content: center;

示例

#bar-container {
  align-items: flex-end;
  display: flex;
  justify-content: center;
}

.bar {
  margin: 0 2px;
  background: lightgreen;
  width: 10px;
}
<div id="bar-container">

  <div class="bar" style="height: 70px"></div>
  <div class="bar" style="height: 170px"></div>
  <div class="bar" style="height: 20px"></div>
  <div class="bar" style="height: 120px"></div>
  <div class="bar" style="height: 50px"></div>
  <div class="bar" style="height: 100px"></div>
  <div class="bar" style="height: 90px"></div>
  <div class="bar" style="height: 110px"></div>
  <div class="bar" style="height: 40px"></div>
  <div class="bar" style="height: 30px"></div>
  <div class="bar" style="height: 140px"></div>

</div>

【讨论】: