TL; DR
一个想法是保持两者的边界.除了简单地使颜色透明之外,不要使颜色透明,以使两者的大小(包括边框填充)始终相同.
div.test {
background-color: red;
box-sizing: border-box;
display: inline-block;
border: 5px solid;
text-align: center;
padding: 50px;
}
div.test:first-of-type {
border-color: transparent;
}
为什么?
设置高度/宽度时,您要明确定义两者都具有固定的大小,并且此大小将包括边框,填充和内容.正如我们在the documentation中所读到的:
border-box
tells the browser to account for any border and padding in
the values you specify for an element’s width and height. If you set
an element’s width to 100 pixels, that 100 pixels will include any
border or padding you added, and the content box will shrink to absorb
that extra width.
和
Here the dimensions of the element are calculated as: width = border +
padding + width of the content, and height = border + padding + height
of the content.
现在,假设您在边框为5px的情况下包含45px的填充.在这种情况下,两个框都是相等的,但是您会注意到带有边框的框的内容的高度/宽度为0,因为我们已经达到100px的填充和边框(45px * 2 5px * 2 = 100px),但是另一个框仍然会有一些内容空间:
div.test {
background-color: red;
box-sizing: border-box;
display: inline-block;
border: 5px solid;
text-align: center;
padding: 45px;
height:100px;
width:100px;
vertical-align:middle;
}
div.test:first-of-type {
border:none;
}
现在,如果我们开始增加填充,第一个框仍然有一些内容要缩小(10px),但是第二个框没有!在这种情况下,边框和固定的宽度/高度将无效,因为边框填充超过了100px(46px * 2 5px * 2 = 102px).这就是为什么从45px的填充开始,我们看到两个框之间存在差异,而从50px的填充开始,两个框都没有缩小的内容,但第二个框具有更多的边框,这在逻辑上会使其尺寸更大.定义宽度或高度也变得毫无用处.
换句话说,仅当borderdiv.test {
background-color: red;
box-sizing: border-box;
display: inline-block;
vertical-align:top;
border: 30px solid;
text-align: center;
padding: 5px;
width:100px;
height:100px;
animation:pad 10s infinite linear alternate;
}
div.test:first-of-type {
border:none;
}
@keyframes pad {
0% {padding:5px}
33% {padding:20px}
66% {padding:50px}
100% {padding:100px;}
}
.change:after {
content:"";
animation:change 10s infinite linear alternate;
}
@keyframes change {
0%,33% {content:" (1): same size for both and fixed width/height are respected "}
33.1%,66% {content:" (2): The second box has no more content to shrink, it starts growing (fixed height/width and border-box has no effect)"}
66.1%,100% {content:" (3): Both boxes has no more content to shrink, they will keep growing BUT the second one has more border so bigger size"}
}
we are at state
为了避免这种情况,我们像最初所说的那样对两个元素都保留了相同的填充/边框.