user2334436
user2334436

Reputation: 939

Centering a piece of Text within a div

I'm trying to position some text in the middle of a CSS box. i tired using top:20px; but this moved the whole but rather than the text. any idea how can i do this?

here is my code: 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>

Upvotes: 0

Views: 60

Answers (4)

Damian
Damian

Reputation: 608

Try this my code:

<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',
        });
    });

Demo: http://jsfiddle.net/Silon/caonccjx/

Upvotes: 0

user3913686
user3913686

Reputation:

Example 1


something like: this fiddle.

It uses the css of:

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

which could be quite beneficial for you. :)


Example 2


A more versatile way would be to use span like this demo

which uses:

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

Possible Alternative to (2)


A slight variation of the second example would be to treat the div like a table cell, so altering the above css to:

div {
  display: table;
  width: 250px;
  height: 100px;
  text-align: center;
  border: 1px solid red;
}

span {
  display: table-cell;
  vertical-align: middle;
   
}

And so this should also work for you.

Upvotes: 2

Sorikairo
Sorikairo

Reputation: 798

You could use padding to move the text inside the box.

However, I think that you should create a tag (a box) especially for the text, and give it some css property to center this box in the center of the main div (the main box).

Upvotes: 0

Rohit Azad Malik
Rohit Azad Malik

Reputation: 32162

Try to this

Remove this css in

width:100%;
height:100%;

add this css

left:0;
right:0;
top:0;
bottom:0;
padding-top:20px;

Demo

Upvotes: 0

Related Questions