CSS边框宽度更改布局

问题描述 投票:0回答:4

将边框宽度从1px更改为0px时出现问题。这将改变div的布局。 div应在边距的影响下逐步堆叠,但是当我将边框宽度设置为0px时,顶部边距变为0px。

这是我的代码。

div {
  height: 300px;
  width: 50%;
  margin: 10px;
  border: 1px solid red;
}

.red {
  background-color: #ffcccc;
}

.green {
  background-color: #ccffcc;
}

.blue {
  background-color: #ccccff;
}

.purple {
  background-color: #cccccc
}
<div class="red">
  <div class="green">
    <div class="blue">
      <div class="purple"></div>
    </div>
  </div>
</div>
html css width border margin
4个回答
1
投票

在标准html内容框模型中,宽度仅是框内容的宽度。如果您向其中添加填充和/或边框,则它们将被添加到框的宽度(在您的情况下为50%+ 1px + 1px)。您可以通过选择使用不同的框模型(边框框模型)来更改此行为:在这种情况下,您指定的宽度将始终包括填充和边框。

您可以这样操作:

<style>

    div {
      box-sizing: border-box;

      height: 300px;
      width: 50%;
      margin: 10px;
      border: 1px solid red;
    }

    .red { background-color: #ffcccc; }

    .green { background-color: #ccffcc; }

    .blue { background-color: #ccccff; }

    .purple { background-color: #cccccc}

</style>

有关更多详细信息,请参见herehere


0
投票

这应该做!

<style>

    div {
      height: 300px;
      width: 50%;
      margin: 10px;          
      box-shadow:inset 0px 0px 0px 1px red;
    }

    .red { background-color: #ffcccc; }

    .green { background-color: #ccffcc; }

    .blue { background-color: #ccccff; }

    .purple { background-color: #cccccc}

</style>
<div class="red">
  <div class="green">
    <div class="blue">
      <div class="purple"></div>
    </div>
  </div>
</div>

0
投票

您可以使用此代码

        body {
            margin: 0;
            padding: 0;
        }   
        div {
            height: 300px;
            width: 50%;
            margin: 10px;
            border: 0px solid red;
            float: left;
        }
        .red {
            background-color: #ffcccc;
        }
        .green {
            background-color: #ccffcc;
        }
        .blue {
            background-color: #ccccff;
        }
        .purple {
            background-color: #cccccc;
        }
    <div class="red">
        <div class="green">
            <div class="blue">
                <div class="purple"></div>
            </div>
        </div>
    </div>

0
投票

您可以尝试这个

div {
    height: 300px;
    width: 50%;
    padding: 1px;
    margin:10px;
    border:0px solid red;
}
.red {
    background-color: #ffcccc;
}
.green {
    background-color: #ccffcc;
}
.blue {
    background-color: #ccccff;
}
.purple {
    background-color: #cccccc;
}
<div class="red">
    <div class="green">
        <div class="blue">
            <div class="purple"></div>
        </div>
    </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.