如何在弹性容器中强制居中放置特定元素?

时间:2020-07-23 17:58:51

标签: html css flexbox

我想将div容器内的特定flex居中。您将通过以下代码更好地了解我:

这是我的代码:

<html>

<head>
    <style>
        div.flex_container {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            justify-content: center;
            align-items: baseline;
            align-content: stretch;
        }

        div.red_box {
            background-color: red;
            width: 100px;
            height: 100px;
        }

        div.blue_box {
            background-color: blue;
            width: 100px;
            height: 100px;
        }

        div.yellow_box {
            background-color: yellow;
            width: 100px;
            height: 100px;
        }
    </style>
</head>

<body>
    <div class="flex_container">
        <div class="red_box"></div>
        <div class="blue_box"></div>
        <div class="yellow_box"></div>
    </div>
</body>

</html>

或者这里是JSFiddle代码。

当前,蓝框位于中心位置,但我希望红框位于中心,其他位置位于其右侧。

如何实现此目标,如何在flex容器内强制居中放置特定元素?

编辑:不更改顺序。

谢谢!

2 个答案:

答案 0 :(得分:0)

删除function loadString() { let result = ''; return Observable.create(observer => { libA(n => { result += 'A'.repeat(n); libB(n => { result += 'B'.repeat(n); libC(n => { result += 'C'.repeat(n); libD(n => { result += 'D'.repeat(n); observer.next(result); }); }); }); }) }); } 并将justify-content: center添加到margin-left

red_box
div.flex_container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: baseline;
  align-content: stretch;
}

div.red_box {
  background-color: red;
  width: 100px; height: 100px;
  /*                       ↓ width / 2) */
  margin-left: calc(50% - 50px);
}

div.blue_box {
  background-color: blue;
  width: 100px; height: 100px;
}

div.yellow_box {
  background-color: yellow;
  width: 100px; height: 100px;
}

答案 1 :(得分:0)

您可以使用 CSS订单属性

只需将order: number;添加到box属性中即可。像这样:

div.flex_container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: baseline;
  align-content: stretch;
}

div.red_box {
  background-color: red;
  width: 100px; height: 100px;
  order: 2;
}

div.blue_box {
  background-color: blue;
  width: 100px; height: 100px;
  order: 1;
}

div.yellow_box {
  background-color: yellow;
  width: 100px; height: 100px;
  order: 3;
}
<div class='flex_container'>
  <div class='red_box'></div>
  <div class='blue_box'></div>
  <div class='yellow_box'></div>
</div>

检查this link,了解有关订购弹性商品的更多详细信息