Inner padding and border for a flex-box 2x2 grid

2019-08-22 17:22发布

问题:

I have some issue with 2x2 that I tried to achive using flexbox. I'm trying to achieve something like this.

Every single grid should contain equal amount of padding. Also it's required to add borders only inside. (Within the grid, like a cross)

This is the code that I've come up with but it doesn't work properly.

HTML

<div class="info-box">
<div class="info-item grid1"></div>
<div class="info-item grid2"></div>
<div class="info-item grid3"></div>
<div class="info-item grid4"></div>
</div>

CSS

.info-box {
margin: 2rem auto 0 auto;
text-align: center;
display: flex;
flex-wrap: wrap;
flex-flow: row wrap;
flex-direction: column;
.info-item {
  flex: 1 1 calc(50%);
  background: $light;
  &:nth-child(odd) {
    flex: 0 0 50%;
  }
}
}

How can I have some text inside those individual 4 grids and have some padding around it. Also I'm trying to add the border only inside. Can anyone help me?

回答1:

You can simply achieve the cross using border on the inner elements and padding on the container. Also no need to specify flex direction as in your case it should be row (the default value). Don't forget to add box-sizing: border-box to avoid any overflow issue.

So you may try something like this :

* {
  box-sizing: border-box;
}

.info-box {
  margin: 2rem auto 0 auto;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
  border:1px solid;
  padding:50px;
}

.info-item {
  flex: 1 1 50%;
  min-height: 100px;
  padding:50px;
}
.grid1 {
  border-right:1px solid;
  border-bottom:1px solid;
}
.grid2 {
  border-bottom:1px solid;
  border-left:1px solid;
}
.grid3 {
  border-top:1px solid;
  border-right:1px solid;
}
.grid4 {
  border-left:1px solid;
  border-top:1px solid;
}
<div class="info-box">
  <div class="info-item grid1">1</div>
  <div class="info-item grid2">2</div>
  <div class="info-item grid3">3</div>
  <div class="info-item grid4">4</div>
</div>

Or another solution to avoid the use of border is using pseudo element like this :

* {
  box-sizing: border-box;
}

.info-box {
  margin: 2rem auto 0 auto;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
  border:1px solid;
  padding:50px;
  position:relative;
}
.info-box:before {
  content:"";
  position:absolute;
  background:#000;
  width:2px;
  right:50%;
  margin-right:-1px;
  top:50px;
  bottom:50px;
}
.info-box:after {
  content:"";
  position:absolute;
  background:#000;
  height:2px;
  top:50%;
  margin-top:-1px;
  left:50px;
  right:50px;
}

.info-item {
  flex: 1 1 50%;
  min-height: 100px;
  padding:50px;
}
<div class="info-box">
  <div class="info-item grid1">1</div>
  <div class="info-item grid2">2</div>
  <div class="info-item grid3">3</div>
  <div class="info-item grid4">4</div>
</div>