如何保持带有边框的div并排固定

时间:2015-08-26 23:33:16

标签: css

两个div的宽度设置小于50%不会因为在。之间产生​​小间隙而缩小。

https://jsfiddle.net/54u543e5/

<div id="container">
    <div id="a"></div>
    <div id="b"></div>
</div>

#container {
    width: 50%;
}

#b {
    width: 50%;
    height: 1.5rem;
    background-color: black;
    float: right;
    border-top: 0.2rem solid red;
    border-right: 0.2rem solid red;
}

#a {
    width: 50%;
    height: 1.5rem;
    background-color: grey;
    float: left;
    border-top: 0.2rem solid blue;
    border-left: 0.2rem solid blue;
}

1 个答案:

答案 0 :(得分:2)

问题在于,默认情况下,width不包含边框。因此,如果您使用width: 50%,则总宽度将为50% + 0.2rem,大于50%

因此,您可以:

  • 使用width: calc(50% - 0.2rem),以使总宽度为50% - 0.2rem + 0.2rem,即50%

    #container {
      width: 50%;
    }
    .item {
      width: calc(50% - 0.2rem);
      height: 1.5rem;
      background-color: black;
      float: right;
      border: solid red;
      border-width: 0.2rem 0.2rem 0 0;
    }
    .item + .item {
      background-color: grey;
      float: left;
      border-color: blue;
      border-width: 0.2rem 0 0 0.2rem;
    }
    <div id="container">
      <div class="item"></div>
      <div class="item"></div>
    </div>

  • 使用box-sizing: border-box。这将使width包含边框。

    #container {
      width: 50%;
    }
    .item {
      box-sizing: border-box;
      width: 50%;
      height: 1.5rem;
      background-color: black;
      float: right;
      border: solid red;
      border-width: 0.2rem 0.2rem 0 0;
    }
    .item + .item {
      background-color: grey;
      float: left;
      border-color: blue;
      border-width: 0.2rem 0 0 0.2rem;
    }
    <div id="container">
      <div class="item"></div>
      <div class="item"></div>
    </div>