在一个div中居中放置一段文本
问题描述:
我试图在CSS中间放置一些文本。我厌倦了使用顶部:20px;但是这只是整体而不是文字。任何想法我怎么能做到这一点?在一个div中居中放置一段文本
这里是我的代码:jsfiddle
div {
background: #ff9600;
background: rgba(255, 150, 0, 0.95);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
-moz-box-shadow: inset 0 0 0 1px rgba(255, 182, 78, 1), 0 0 20px rgba(0, 0, 0, 0.6);
-webkit-box-shadow: inset 0 0 0 1px rgba(255, 182, 78, 1), 0 0 20px rgba(0, 0, 0, 0.6);
box-shadow: inset 0 0 0 1px rgba(255, 182, 78, 1), 0 0 20px rgba(0, 0, 0, 0.6);
text-shadow: 1px 1px 0 rgba(0, 0, 0, 0.1);
text-align: center;
z-index: 10;
}
<body>
<div>text</div>
</body>
答
实施例1
类似:this fiddle。
它使用的CSS:
div {
height: 100%;
width: 100%;
background: #000;
font-size: 12px;
font-style: oblique;
color: #FFF;
text-align: center;
margin-top: 20px;
margin-left: 5px;
line-height: 80px;
}
这可能是对你颇有裨益。 :)
实施例2
一个更通用的方法是使用span
像this demo
其使用:
div {
width: 250px;
height: 100px;
line-height: 100px;
text-align: center;
border: 1px solid #123456;
}
span {
display: inline-block;
vertical-align: middle;
line-height: normal;
}
可能爱特纳略去对(2)
第二示例的细微变化可用于治疗象一个表格单元格的格,所以改变上述CSS来:
div {
display: table;
width: 250px;
height: 100px;
text-align: center;
border: 1px solid red;
}
span {
display: table-cell;
vertical-align: middle;
}
所以this也应该工作为你。
答
尝试将此
在
width:100%;
height:100%;
删除这个CSS添加此CSS
left:0;
right:0;
top:0;
bottom:0;
padding-top:20px;
答
你可以使用padding
移动箱中的文本。
但是,我认为你应该为文本创建一个标签(一个盒子),并给它一些CSS属性来将这个盒子放在主div(主盒子)的中心。
答
试试这个我的代码:
<div>
<span class="vertical-text">
TEXT
</span>
</div>
$('.vertical-text').each(function()
{
parent_height = $(this).parent().height();
$(this).parent().css(
{
'height': parent_height + 'px',
'line-height': parent_height + 'px',
});
$(this).css(
{
'line-height': 'normal',
'display': 'inline-block',
});
});
用于填充顶:20px的; like this – 2014-10-09 08:33:52
将'padding-top:20px;'和'box-sizing:border-box;'添加到'div' - http://jsfiddle.net/zx3rzwzt/ – Anonymous 2014-10-09 08:35:08