简体   繁体   English

CSS文本居中于DIV内部

[英]CSS Text centered inside a DIV

I am trying to achieve something and can't manage to do so. 我正在努力实现某些目标而无法实现这一目标。

I have a div with fixed HEIGHT & WIDTH. 我有一个固定高度和宽度的div。 I want the text to be centered vertically. 我希望文本垂直居中。

up till now I managed to do so: 到目前为止我设法做到了:

<div>
   <a>this is a long text</a>
</div>

and it will look like this 它看起来像这样

-------------
This is a long
    text
-------------

which is great 这很棒

But if the line won't wrap it will look like this 但是如果线条不会换行,它将会是这样的

------------
This is short

-------------

.the-div
{
height:29px;
line-height:14px !important;
}

.the-a
{
font-size:12px;
}

I need this to be valigned as well! 我需要这个也是值得的!

I tried using line-height and to play with is with JS to understand if its wrapping or not and then changing the line-height accordingly 我尝试使用行高并与JS一起玩,以了解它是否包装,然后相应地改变行高

Thanks for the help 谢谢您的帮助

To be vertical aligned as well, you'll need to use some display as table hacks. 要进行垂直对齐,您还需要使用一些显示作为表格黑客。 This will allow you to use vertical-align:middle; 这将允许你使用vertical-align:middle; , achieving the look I believe you desire. ,实现我相信你渴望的外观。

Example

.the-a
{
font-size:12px;
vertical-align: middle;
}

if you make the line-height same as the height of div, it will automatically vertical centered 如果你使行高与div的高度相同,它将自动垂直居中

the-div
{
height:29px;
line-height:29px !important;
}
div a{
margin-top:auto;
margin-bottom:auto;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM