简体   繁体   中英

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. 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

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; , 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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