是否可以根据元素的大小不同地垂直对齐 :before ?
Is it possible to vertically align a :before differently depending on the size of the element?
我有一个 :before
元素,我想根据它附加到的元素的高度以不同方式垂直对齐。我将它与 <blockquote>
一起使用,但我相信我的问题更普遍。
我有以下jsfiddle来说明:https://jsfiddle.net/06mf93kx/
基本上我希望 :before
元素与段落的顶部对齐(因为它在 fiddle 中;第二个引号在那里是正确的。)但是,如果段落只有一行,那么我希望该段落相对于 :before
元素垂直居中,如下所示:
+-------+
| |
| | Pithy quote.
| |
+-------+
有没有办法在CSS中做到这一点而无需借助JS来测量段落大小和调整样式?
一些我已经尝试过的东西: 我已经在 <blockquote>
上尝试了 line-height: 30px
并且这产生了单行的期望结果案例,但当然在多行案例中将行隔开。我已经尝试在 <blockquote>
上使用 min-height: 30px
,在 <p>
上使用 top: 50%
,但这似乎没有任何改变。
自从引入灵活布局后,一切变得非常简单。我复制了你的 jsFiddle HTML/CSS 并将 display
更改为 flex
,并且我使用 align-items
将内部元素垂直居中。
blockquote {
margin-left: 20%;
}
blockquote:first-child {
display: flex;
align-items: center;
}
blockquote:before {
content: url('http://placehold.it/30x30');
width: 30px;
height: 30px;
margin-right: 1rem;
float: left;
margin-left: -15%;
}
<blockquote>
<p>
Pithy quote.
</p>
</blockquote>
<hr/>
<blockquote>
<p>
This is a long quote; there's a lady who's sure all that glitters is gold and she's buying a stairway to heaven. When she gets there she knows, if the stores are all closed, with a word she can get what she came for.
</p>
</blockquote>
CSSTricks has an excellent guide 成为创建灵活布局的专家。
最后是 Matías 的 CSS tricks link 为我指明了正确的方向。
这是我希望它执行的操作:https://jsfiddle.net/8utbj2o7/
而不是 align-items: center
,我使用 align-self
:
blockquote:before {
align-self: flex-start;
}
blockquote p {
align-self: center;
}
如果 <p>
元素的高度低于 :before
元素,这会使 元素仅 居中。
我有一个 :before
元素,我想根据它附加到的元素的高度以不同方式垂直对齐。我将它与 <blockquote>
一起使用,但我相信我的问题更普遍。
我有以下jsfiddle来说明:https://jsfiddle.net/06mf93kx/
基本上我希望 :before
元素与段落的顶部对齐(因为它在 fiddle 中;第二个引号在那里是正确的。)但是,如果段落只有一行,那么我希望该段落相对于 :before
元素垂直居中,如下所示:
+-------+
| |
| | Pithy quote.
| |
+-------+
有没有办法在CSS中做到这一点而无需借助JS来测量段落大小和调整样式?
一些我已经尝试过的东西: 我已经在 <blockquote>
上尝试了 line-height: 30px
并且这产生了单行的期望结果案例,但当然在多行案例中将行隔开。我已经尝试在 <blockquote>
上使用 min-height: 30px
,在 <p>
上使用 top: 50%
,但这似乎没有任何改变。
自从引入灵活布局后,一切变得非常简单。我复制了你的 jsFiddle HTML/CSS 并将 display
更改为 flex
,并且我使用 align-items
将内部元素垂直居中。
blockquote {
margin-left: 20%;
}
blockquote:first-child {
display: flex;
align-items: center;
}
blockquote:before {
content: url('http://placehold.it/30x30');
width: 30px;
height: 30px;
margin-right: 1rem;
float: left;
margin-left: -15%;
}
<blockquote>
<p>
Pithy quote.
</p>
</blockquote>
<hr/>
<blockquote>
<p>
This is a long quote; there's a lady who's sure all that glitters is gold and she's buying a stairway to heaven. When she gets there she knows, if the stores are all closed, with a word she can get what she came for.
</p>
</blockquote>
CSSTricks has an excellent guide 成为创建灵活布局的专家。
最后是 Matías 的 CSS tricks link 为我指明了正确的方向。
这是我希望它执行的操作:https://jsfiddle.net/8utbj2o7/
而不是 align-items: center
,我使用 align-self
:
blockquote:before {
align-self: flex-start;
}
blockquote p {
align-self: center;
}
如果 <p>
元素的高度低于 :before
元素,这会使 元素仅 居中。