Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

css - How to create "collapsed" borders around flex items and their container?

I have the following layout:

#limited-width {
  width: 100%;
  max-width: 200px;
  margin: 0 auto;
  font-size: 18px;
}
ul {
  display: flex;
  flex-flow: row wrap;
  list-style: none;
  padding: 0;
  margin: 20px;
}
ul > li {
  display: block;
  text-align: center;
  flex: 1 0 auto;
  max-width: 100%;
  box-sizing: border-box;
  margin: 0;
  padding: 4px 7px;
  border: 2px solid rgba(0,0,0,.3);
  background-color: rgba(0,0,0,.03);
}
<div id="limited-width">
  <ul>
    <li>Apple</li>
    <li>Orange</li>
    <li>Pineapple</li>
    <li>Banana</li>
    <li>Tomato</li>
    <li>Pear</li>
    <li>Lemon</li>
  </ul>
</div>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There are two primary ways to achieve this. Under each method you will find a working demo that you can expand to see how it behaves. Hovering over elements will give them a red border to make choosing the approach that works best for you easier.

Parent-child border alignment

You need to define the border like this:

ul, ul > li {
  border-style: solid;
  border-color: rgba(0,0,0,.3);
}
ul      { border-width: 2px  0   0  2px }
ul > li { border-width:  0  2px 2px  0  }

The key here is in the border-width property:

  • On the container, the values for the top and left are set to the desired size while the right and bottom are set to 0
  • On the items, the values for the right and bottom are set to the desired size while the top and left are set to 0

By doing this, the borders will add up in a way that they form a nicely collapsed, consistent border around the elements and the container.

:hover { border-color: red }
#limited-width {
  width: 100%;
  max-width: 200px;
  margin: 0 auto;
  font-size: 18px;
}
ul, ul > li {
  border-style: solid;
  border-color: rgba(0,0,0,.3);
}
ul {
  display: flex;
  flex-flow: row wrap;
  list-style: none;
  padding: 0;
  margin: 20px;
  border-width: 2px 0 0 2px;
}
ul > li {
  display: block;
  text-align: center;
  flex: 1 0 auto;
  max-width: 100%;
  box-sizing: border-box;
  margin: 0;
  padding: 4px 7px;
  border-width: 0 2px 2px 0;
  background-color: rgba(0,0,0,.03);
}
<div id="limited-width">
  <ul>
    <li>Apple</li>
    <li>Orange</li>
    <li>Pineapple</li>
    <li>Banana</li>
    <li>Tomato</li>
    <li>Pear</li>
    <li>Lemon</li>
  </ul>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...