Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS text in center of background image

Tags:

html

css

how can I center text on following (Sorry I'm new to CSS):

alt text

CSS:

suggestion_active { 
    background-image: url(../images/suggestion_active.jpg);
    background-repeat:no-repeat;
    position:inherit;
    float:inherit;
    width: 100px; 
    height: 36px;
}

suggestion_active_text {
    possition: absolute;
    font-family: "Lucida Grande", Tahoma;
    font-size: 12px;
    font-weight: lighter;
    text-align: center;
    color:#000;
    vertical-align: middle;
    padding:0px;
}

html:

 <suggestion_active><suggestion_active_text>1</suggestion_active_text></suggestion_active>

Also it would be nice if you tell me the best practices of how to do this :)

like image 825
Lukas Šalkauskas Avatar asked Nov 21 '10 19:11

Lukas Šalkauskas


2 Answers

Set text-align: center; to center the text horizontally, and set line-height: [heightofbox]; to center the text vertically.

Here is a simple example of that


Note that, if you are working with invalid HTML elements, you need to set them as block elements. So, this should do the trick:

customEl {
  display: block;
  ...
}
like image 99
Harmen Avatar answered Nov 12 '22 08:11

Harmen


Bit more modern answer maybe?

  1. Create a div
  2. Place text inside the div

Then using flexbox style div as follows:

  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  justify-content: center;
  align-items: center;

ALTERNATIVELY for more dynamic positioning

set your background image div to

  positiion: relative;

AND your text box div to include

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  • This allows you to move text for instance 20% from the top instead of 50%.
  • translate(-50%,-50%) realigns the anchor of the text div to be in the center, which will be noticeable if you have longer text.
like image 4
Aquasar Avatar answered Nov 12 '22 08:11

Aquasar