html - 在伪元素未显示之前

标签 html css

div {
    width: 100px;
    height: 100px;
    background: red;
}

div:before {
    content: "";
    width: 100px;
    height:30px;
    background: yellow;
}

为什么未设置位置值(分别为相对值和绝对值)时,div 元素上方不显示 before 伪元素?

最佳答案

::before::after伪元素默认是display:inlinewidthheight不会影响。

您可以将伪元素设置为display:block

div {
  width: 100px;
  height: 100px;
  background: red;
}

div:before {
  content: "";
  display: block;
  width: 100px;
  height: 30px;
  background: yellow;
}
<div></div>

View on JSFiddle

另见 What is the default display property of the :before and :after pseudo-elements?

关于html - 在伪元素未显示之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50009402/

相关文章:

javascript - 不断出现提示

html - CSS: 可以 object-fit:cover,有一个起始位置

jquery - 使用内联 offsetparent 获取元素左/顶部的实际偏移量

html - CSS 页脚对齐在 FF 和 IE 中运行

css - 通过 CSS 根据高度设置元素宽度

javascript - 轮播 HTML 不工作

html - HTML 中错误的 RTL 布局 - CSS 覆盖不起作用

css - fullpage.js:使用 CSS 淡入幻灯片

css - Bootstrap 在纯 html 和 rails 中有不同的行为

javascript - 检查网站在不同浏览器上的外观