我想知道将p元素中的文本对齐为垂直居中.
这是我的风格:
p.event_desc {
font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 14px;
height: 35px;
margin: 0px;
}
Run Code Online (Sandbox Code Playgroud)
和HTML:
<p class="event_desc">Lorem ipsum.</p>
Run Code Online (Sandbox Code Playgroud)
Dip*_*pak 55
试试这些风格:
p.event_desc {
font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 14px;
height:75px;
margin: 0px;
display: table-cell;
vertical-align: middle;
padding: 10px;
border: 1px solid #f00;
}Run Code Online (Sandbox Code Playgroud)
<p class="event_desc">lorem ipsum</p>Run Code Online (Sandbox Code Playgroud)
And*_*ich 24
你可以用line-height它.只需将其设置为p标签的确切高度即可.
p.event_desc {
line-height:35px;
}
Run Code Online (Sandbox Code Playgroud)
如果涉及表格或设置 line-height 的答案对您不起作用,您可以尝试将 p 元素包装在 div 中,并相对于父 div 的高度设置其位置的样式。
.parent-div{
width: 100px;
height: 100px;
background-color: blue;
}
.text-div{
position: relative;
top: 50%;
transform: translateY(-50%);
}
p.event_desc{
font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
color: white;
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<div class="parent-div">
<div class="text-div">
<p class="event_desc">
MY TEXT
</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
因此,就我个人而言,我不确定最好的方法,但我发现对于垂直对齐效果很好的一件事是使用 Flex,因为您可以证明它的内容合理!
假设您有以下 HTML 和 CSS:
.paragraph {
font-weight: light;
color: gray;
min-height: 6rem;
background: lightblue;
}Run Code Online (Sandbox Code Playgroud)
<h1 class="heading"> Nice to meet you! </h1>
<p class="paragraph"> This is a paragraph </p>Run Code Online (Sandbox Code Playgroud)
我们最终得到一个不垂直居中的段落,现在如果我们使用 Flex Column 并应用最小高度 + BG,我们会得到以下结果:
.myflexbox {
min-height: 6rem;
display: flex;
flex-direction: column;
justify-content: center;
background: lightblue;
}
.paragraph {
font-weight: light;
color: gray;
}Run Code Online (Sandbox Code Playgroud)
<h1 class="heading"> Nice to meet you! </h1>
<div class="myflexbox">
<p class="paragraph"> This is a paragraph </p>
</div>Run Code Online (Sandbox Code Playgroud)
然而,在某些情况下,您不能如此轻松地将 P 标签包装在 div 中,在 P 标签上使用 Flexbox 是完全可以的,即使这不是最好的做法。
.myflexparagraph {
min-height: 6rem;
display: flex;
flex-direction: column;
justify-content: center;
background: lightblue;
}
.paragraph {
font-weight: light;
color: gray;
}Run Code Online (Sandbox Code Playgroud)
<h1 class="heading"> Nice to meet you! </h1>
<p class="paragraph myflexparagraph"> This is a paragraph </p>Run Code Online (Sandbox Code Playgroud)
我不知道这是好还是坏,但如果这只能帮助某个地方的一个人,那就再多一个人了!