css边框实现高度,CSS-Box-Sizing:没有声明的高度/宽度的边框

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;

}

aa
aa

为什么?

设置高度/宽度时,您要明确定义两者都具有固定的大小,并且此大小将包括边框,填充和内容.正如我们在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;

}

aa
aa

UKwrh.png

现在,如果我们开始增加填充,第一个框仍然有一些内容要缩小(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

aa
aa

为了避免这种情况,我们像最初所说的那样对两个元素都保留了相同的填充/边框.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值