英文:
::before element doesn't show up without display:flex
问题
<!-- 开始代码片段: js 隐藏: false 控制台: true Babel: false -->
<!-- 语言: lang-css -->
.quote {
display: flex;
/*?? without this, ::before doesn't show up*/
}
.quote::before {
content: "";
min-width: 8px;
background-color: #F7DF94;
}
<!-- 语言: lang-html -->
<div class="quote">
Hello World
</div>
<!-- 结束代码片段 -->
我不确定为什么如果我删除 `display: flex`,::before 元素就不会显示出来。
在 [JSbin 这里](https://jsbin.com/hodamup/edit?html,css,output) 的代码片段。
英文:
With below Code
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.quote {
display: flex;
/*?? without this, ::before doesn't show up*/
}
.quote::before {
content: "";
min-width: 8px;
background-color: #F7DF94;
}
<!-- language: lang-html -->
<div class="quote">
Hello World
</div>
<!-- end snippet -->
I am not sure why the ::before element won't show up if I remove the display: flex
.
Code snippet in JSbin here
答案1
得分: 2
:before
元素之所以不会 "显示" 是因为默认的显示属性类似于 display: inline;
,而你不能设置行内元素的宽度或高度。
MDN 上对宽度的定义:
> 适用于:所有元素,但不包括非替换的内联元素、表格行和行组
当你在父元素上设置 display: flex;
时,子元素会像 flex 项目一样,可以具有宽度/高度。
对于 flex 项目,align-items
的初始值是 normal
(在这个上下文中的行为类似于 stretch 请看这里)。这个值使项目占据100%的高度。
如果你不想在父元素上使用 display: flex;
,你可以将伪元素的默认属性更改为 display: inline-block;
,但你需要指定一个高度,否则它也不会显示。请注意,伪元素和内容之间会有一个空白。
这里有一个示例:
<!-- language: lang-css -->
.quote::before {
display: inline-block;
content: "";
min-width: 8px;
min-height: 8px;
background-color: #F7DF94;
}
<!-- language: lang-html -->
<div class="quote">
Hello World
</div>
英文:
The :before
element doesn't "show up" because the default display property acts like display: inline;
and you cannot set the with or height of an inline element.
Definition of width on MDN :
> Applies to: all elements but non-replaced inline elements, table rows,
> and row groups
[reference] (emphasis mine)
And the same goes for height, see here
When you set display: flex;
on the parent, the children act like flex items that can have a width / height.
The initial value of align-items
for flex items is normal
(behaves like stretch in this context see here). This value makes the items take 100% height.
If you don't want to use display: flex;
on the parent, you could change the default property of the pseudo element to display: inline-block;
but you will need to specify a height otherwise it won't display either. Note that there will be a white-space between the pseudo element and the content.
Here is an example :
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.quote::before {
display:inline-block;
content: "";
min-width: 8px;
min-height: 8px;
background-color: #F7DF94;
}
<!-- language: lang-html -->
<div class="quote">
Hello World
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论