Hai*_*ood 34 html css centering
我正在使用一个100%的父div高度的div.
div只包含一行文本.
div不能有固定的高度.
所以我的问题是.
如何垂直居中文本行?
我尝试过使用:
display: table-cell;
line-height:200%;
Run Code Online (Sandbox Code Playgroud)
如果重要的是div绝对定位.
.requests {
position: absolute;
right: 0;
height: 100%;
width: 50px;
padding: 0 10px;
background-color: #69A4B5;
display: table-cell;
vertical-align: middle;
border-bottom-right-radius: 5px;
}
Run Code Online (Sandbox Code Playgroud)
elb*_*ire 31
编辑:最好和最简单的方法(目前在2015年 2017年)使用flexbox:
.parent-selector {
display: flex;
align-items: center;
}
Run Code Online (Sandbox Code Playgroud)
就是这样:D
看看这个工作示例:http://jsfiddle.net/qj2Jr/114/
旧答案:你可以使用vertical-align:middle如果你还指定display:table-cell;
.div {
display: table-cell;
vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)
工作示例:http://jsfiddle.net/qj2Jr/1/
如果它不起作用,您可以尝试将其父级设置为display: table;:
.parent-selector {
display: table;
}
Run Code Online (Sandbox Code Playgroud)
编辑:在这个问题中你有这个方法加上这个问题所涵盖的所有方法:如何用CSS垂直居中文本?
gre*_*gan 27
这个答案不再是最好的答案......请参阅下面的flexbox答案!
为了使它完全居中(如大卫的答案所述),你需要添加一个负的上边距.如果您知道(或强制)只有一行文本,您可以使用:
margin-top: -0.5em;
例如:
http://jsfiddle.net/45MHk/623/
//CSS:
html, body, div {
height: 100%;
}
#parent
{
position:relative;
border: 1px solid black;
}
#child
{
position: absolute;
top: 50%;
/* adjust top up half the height of a single line */
margin-top: -0.5em;
/* force content to always be a single line */
overflow: hidden;
white-space: nowrap;
width: 100%;
text-overflow: ellipsis;
}
//HTML:
<div id="parent">
<div id="child">Text that is suppose to be centered</div>
</div>?
Run Code Online (Sandbox Code Playgroud)
最初接受的答案不会垂直居中于文本的中间(它基于文本的顶部居中).所以,如果你的父母不是很高,它就不会看起来居中,例如:
//CSS:
#parent
{
position:relative;
height: 3em;
border: 1px solid black;
}
#child
{
position: absolute;
top: 50%;
}?
//HTML:
<div id="parent">
<div id="child">Text that is suppose to be centered</div>
</div>?
Run Code Online (Sandbox Code Playgroud)
尝试这个http://jsfiddle.net/Husamuddin/ByNa3/
它适用于我,
css
.table {
width:100%;
height:100%;
position:absolute;
display:table;
}
.cell {
display:table-cell;
vertical-align:middle;
width:100%;
height:100%:
}
Run Code Online (Sandbox Code Playgroud)
和HTML
<div class="table">
<div class="cell">Hello, I'm in the middle</div>
</div>
Run Code Online (Sandbox Code Playgroud)
由于它是绝对定位的,您可以使用top:50%在中心垂直对齐.
但是你遇到了比你想要的更大的页面问题.为此,您可以使用overflow:hidden为父div.这就是我用来创造相同效果的东西:
CSS:
div.parent {
width: 100%;
height: 300px;
position: relative;
overflow: hidden;
}
div.parent div.absolute {
position: absolute;
top: 50%;
height: 300px;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div class="parent">
<div class="absolute">This is vertically center aligned</div>
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95178 次 |
| 最近记录: |