[英]Closest Positioned Ancestor width & height doesn't work on HTML Tbody
[英]Why doesn't width/height work with non positioned pseudo elements?
我想將::before偽元素的寬度設置為 80%。 如果我使用定位,那么一切正常,但如果我不使用它,那么一切都會失敗。
你能解釋一下為什么百分比寬度在沒有定位的情況下不起作用嗎? 如果可以,請添加一些對規范的引用
.positioned { position: relative; height: 15px; background-color: aquamarine; margin-bottom: 10px; } .positioned::before { position: absolute; content: ""; background: red; width: 80%; height: 100%; } .not-positioned { height: 15px; background-color: aquamarine; margin-bottom: 10px; } .not-positioned::before { content: ""; background: red; width: 80%; height: 100%; }
<div class="positioned"></div> <div class="not-positioned"></div>
首先,這與百分比值無關。 即使使用像素值並且寬度和高度都不起作用,您也會得到相同的結果。
偽元素是內聯元素,它們的寬度/高度僅由其內容定義,使用 CSS 設置的寬度/高度將被忽略。
在 CSS 中,
::before
創建一個偽元素,它是被選元素的第一個子元素。 它通常用於向具有 content 屬性的元素添加裝飾性內容。 默認情況下是內聯的。 參考
寬度
此屬性不適用於不可替換的內聯元素。 未替換的內聯元素框的內容寬度是其中渲染內容的寬度ref
'height' 屬性不適用。 內容區域的高度應根據字體... ref
通過使偽元素position:absolute
,您現在將考慮適用於 絕對定位元素的規則,以計算寬度和高度。 您還將注意到該元素將在顯示中具有block
的計算值。
您還應該注意定位元素的使用,這意味着相對、絕對、固定或粘性但使元素position:relative
將使其保持為內聯級別元素,您仍然不能使用寬度/高度。
.positioned { position: relative; height: 15px; background-color: aquamarine; margin-bottom: 10px; } .positioned::before { position: relative; content: ""; background: red; width: 80%; height: 100%; } .not-positioned { height: 15px; background-color: aquamarine; margin-bottom: 10px; } .not-positioned::before { content: ""; background: red; width: 80%; height: 100%; }
<div class="positioned"></div> <div class="not-positioned"></div>
這就是說,如果您想獲得相同的視覺效果,可以通過考慮漸變來簡化代碼:
.positioned { position: relative; height: 15px; background: linear-gradient(red,red) left/80% 100% no-repeat, aquamarine; margin-bottom: 10px; }
<div class="positioned"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.