大家都知道position设置为absolute以及float定位会使元素脱离正常流,如果父元素没有设置高度的话,他们不会把父元素的高度撑开。对于float元素可以把父元素设置overflow:hidden或者其他可以为父元素创建BFC的方法来解决这个问题,但是为什么对于绝对定位的元素这些办法行不通呢?求指教
2 回答
神不在的星期二
TA贡献1963条经验 获得超6个赞
W3C标准的算法里,float可能参与父级高度计算,但position:absolute;始终不参与父级计算。就是这样设计的,没辙:W3CCSS2.110.6.3规定了未创建BFC的非替换块级元素的高度计算规则:Thissectionalsoappliestoblock-levelnon-replacedelementsinnormalflowwhen'overflow'doesnotcomputeto'visible'buthasbeenpropagatedtotheviewport.If'margin-top',or'margin-bottom'are'auto',theirusedvalueis0.If'height'is'auto',theheightdependsonwhethertheelementhasanyblock-levelchildrenandwhetherithaspaddingorborders:Theelement'sheightisthedistancefromitstopcontentedgetothefirstapplicableofthefollowing:thebottomedgeofthelastlinebox,iftheboxestablishesainlineformattingcontextwithoneormorelinesthebottomedgeofthebottom(possiblycollapsed)marginofitslastin-flowchild,ifthechild'sbottommargindoesnotcollapsewiththeelement'sbottommarginthebottomborderedgeofthelastin-flowchildwhosetopmargindoesn'tcollapsewiththeelement'sbottommarginzero,otherwise如上述分点,分项1定义了line-box撑高容器,分项2和3定义了常规流块级元素撑高容器(margin折叠与否的两种情况),否则为0。W3CCSS2.110.6.7规定了创建了BFC的元素(blockformattingcontextroots)的高度计算规则:Ifitonlyhasinline-levelchildren,theheightisthedistancebetweenthetopofthetopmostlineboxandthebottomofthebottommostlinebox.Ifithasblock-levelchildren,theheightisthedistancebetweenthetopmargin-edgeofthetopmostblock-levelchildboxandthebottommargin-edgeofthebottommostblock-levelchildbox.Absolutelypositionedchildrenareignored,andrelativelypositionedboxesareconsideredwithouttheiroffset.Notethatthechildboxmaybeananonymousblockbox.Inaddition,iftheelementhasanyfloatingdescendantswhosebottommarginedgeisbelowtheelement'sbottomcontentedge,thentheheightisincreasedtoincludethoseedges.Onlyfloatsthatparticipateinthisblockformattingcontextaretakenintoaccount,e.g.,floatsinsideabsolutelypositioneddescendantsorotherfloatsarenot.这里规则大致跟上方一样,不同点在于margin不再折叠和float高度参与计算。总之呢,在“撑高父容器圈”里面没有绝对定位元素的地位。
明月笑刀无情
TA贡献1828条经验 获得超4个赞
position为absolute的元素是相对于离他最近的position不为static的父级元素定位的,它不会占据父元素的空间,所以也不会撑起父级元素,这点和设置float的元素不一样,唯一的办法是给父级元素设置高度。
添加回答
举报
0/150
提交
取消