有两个元素与flexbox共享相同的行

时间:2018-05-31 01:30:46

标签: css flexbox

如果我使用flexbox证明一系列元素是合理的,那么可以让2个元素共享一行吗?

例如,举个例子:



.outer {
  display: flex;
  flex-direction: column;
  margin-left: auto;
  margin-right: auto;
  width: 50px;
}
.outer .inner {
  width: 50px;
  height: 50px;
  background-color: blue;
  margin-bottom: 20px;
  font-size: 24px;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

<div class="outer">
  <div class="inner">1</div>
  <div class="inner">2</div>
  <div class="inner">3</div>
  <div class="inner">4</div>
  <div class="inner">5</div>
  <div class="inner">6</div>
  <div class="inner">7</div>
</div>
&#13;
&#13;
&#13;

元素是直列。是否可以选择某些元素来共享这样的行:

enter image description here

2 个答案:

答案 0 :(得分:4)

你可以试试这个。

我所做的是将.outer设置为flex-flow:row wrap;并设置其width

然后设置margin

.outer .inner:nth-child(3),.outer .inner:nth-child(4)

让孩子3和4设置其marginwidth仍然不会超过.outer的宽度,这样他们仍然会相互内联并且另一个孩子将占据整行,因为他们marginwidth等于.outer的宽度

.outer {
  display: flex;
  flex-flow: row wrap;
  margin-left: auto;
  margin-right: auto;
  width: 120px;
  justify-content: center;
  align-items: center;
}
.outer .inner {
  width: 50px;
  height: 50px;
  margin-left: 35px;
  margin-right: 35px;
  margin-bottom: 20px;
  background-color: blue;
  font-size: 24px;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.outer .inner:nth-child(3),
.outer .inner:nth-child(4){
  margin-left: 5px;
  margin-right: 5px;
}
<div class="outer">
  <div class="inner">1</div>
  <div class="inner">2</div>
  <div class="inner">3</div>
  <div class="inner">4</div>
  <div class="inner">5</div>
  <div class="inner">6</div>
  <div class="inner">7</div>
</div>

答案 1 :(得分:2)

您可以尝试这样的事情:

.outer {
  display: flex;
  margin:auto;
  flex-wrap:wrap;
  width: 50px;
}
.outer .inner {
  width: 50px;
  height: 50px;
  background-color: blue;
  margin-bottom: 20px;
  font-size: 24px;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.outer .inner:nth-child(3),.outer .inner:nth-child(4) {
  width:25px;
  position:relative;
}
.outer .inner:nth-child(3):before,.outer .inner:nth-child(4):before {
  content:"";
  position:absolute;
  top:0;
  bottom:0;
  left:-12px;
  right:-12px;
  background:blue;
  z-index:-1;
}

.outer .inner:nth-child(3) {
  transform:translateX(-20px)
}
.outer .inner:nth-child(4) {
  transform:translateX(20px)
}
<div class="outer">
  <div class="inner">1</div>
  <div class="inner">2</div>
  <div class="inner">3</div>
  <div class="inner">4</div>
  <div class="inner">5</div>
  <div class="inner">6</div>
  <div class="inner">7</div>
</div>