padding-top的值用的是百分比,实际显示的不是父元素高度的百分比,而是宽度的百分比!margin-top同理

本文探讨了在CSS布局中,当使用百分比作为padding-top属性值时遇到的一个计算问题。作者通过实例发现,实际计算结果与预期不符,并进一步分析了问题原因在于父元素高度的实际值与预期值存在偏差。

浏览器直接显示,height是662px,我自己的计算padding-top是662px*30% = 198.6px。

而实际是162px,反推过去,162px / 30% = 540px。即父元素的宽!



确定元素大小 在 CSS 的默认盒子模型中,当我们指定一个CSS元素的高度宽度时,只是指定了内容的宽度高度。一个元素的大小,还包括其外边距、内边距和边框。通过box-sizing 属性可以更改计算元素宽度高度的默认的 CSS 盒子模型。 box-sizing box-sizing 属性可以 设置为 content-box 或者 border-box。 /* 关键字 */ box-sizing: content-box; box-sizing: border-box; 其分别含义如下: content-box 如果设置 content-box 的 宽度为 width,高度为 height,元素实际布局占得宽度为 Width,高度为 Height。元素布局的实际大小,需要加上padding和border的大小。 所以, 元素布局所占宽度Width计算方法为: Width = width + padding-left + padding-right + border-left + border-right 元素布局所占高度Height计算方法为: Height = height + padding-top + padding-bottom + border-top + border-bottom border-box 如何设置 border-box 的 宽度为 width,高度为 height,元素实际布局占得宽度为 Width,高度为 Height。元素布局的实际大小和 border-box 设置相同。 所以: 布局所占宽度 Width计算方法为: Width = width(包含padding-left + padding-right + border-left + border-right) 布局所占高度 Height计算方法为: Height = height(包含padding-top + padding-bottom + border-top + border-bottom) 修改bix-sizing中width和height属性,使得box-sizing类的元素内容大小与content-sizing的内容大小相同。 内外边距重叠 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>盒模型——确定元素大小</title> <style type="text/css"> .content-box { width: 160px; height: 80px; padding: 20px; border: 8px solid red; background: yellow; box-sizing: content-box; /* Total width: 160px + (2 * 20px) + (2 * 8px) = 216px Total height: 80px + (2 * 20px) + (2 * 8px) = 136px Content box width: 160px Content box height: 80px */ } .border-box { /***************** BEGIN *****************/ /***************** END *****************/ padding: 20px; border: 8px solid red; background: yellow; box-sizing: border-box; } </style> </head> <body> <div class="content-box">Content box</div> <br> <div class="border-box">Border box</div> </body> </html> import os,sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) from util2 import * html_content = getPrasedHtml() html = html_content doc = pq(html) tag = input() result = 'false' if tag == 'body': result = 'body元素设置失败' style = doc(tag).attr('style') if style == 'margin:0; padding:20px; border:10px solid lightsalmon': result = 'body元素设置成功' if tag == '.border-box': result = 'border-box元素设置失败' style = doc(tag).attr('style') if style == 'background:yellow; border:8px solid red; box-sizing:border-box; height:136px; padding:20px; width:216px': result = 'border-box元素设置成功' checkHTMLGrammar() checkCSSGrammar() print(result,end="")
最新发布
09-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值