Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
869 views
in Technique[技术] by (71.8m points)

html - Equal width using flex and border-box

I am using box-sizing: border-box; with varying border thicknesses within a flexbox. I want the elements within the flexbox to have equal widths, but it calculates the width of the element without the borders.

Here is an example: the width of my container is 100px, so each element should be 20px; however they are 19.2px (x4) and 23.2px.

.container {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100px;
}

.container .block {
  height: 28px;
  flex: 1;
  border: 1px solid black;
  box-sizing: border-box;
}

.container .block.selected {
  border: 3px solid blue;
}
<div class="container">
  <span class="block">0</span>
  <span class="block">1</span>
  <span class="block selected">2</span>
  <span class="block">3</span>
  <span class="block">4</span>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The box-sizing: border-box is used to change the default CSS box model used to calculate width and height of the elements.

So would be like this:

  • total width = border + padding + content width

    and

  • total height = border + padding + content height

But that doesn't happen in flex-grow, but in flex-basis

Here is a good tutorial about flexbox


So you can use flex:0 20% instead of flex:1,

.container {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100px;
}

.container .block {
  height: 28px;
  flex: 0 20%;
  border: 1px solid black;
  box-sizing: border-box;
}

.container .block.selected {
  border: 3px solid blue;
}
<div class="container">
  <span class="block">0</span>
  <span class="block">1</span>
  <span class="block selected">2</span>
  <span class="block">3</span>
  <span class="block">4</span>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...