CSS text in the center of the background image

how can I focus the text on the 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> 

It would also be nice if you would tell me the best practices on how to do this :)

+4
source share
5 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 this


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; ... } 
+11
source

You can remove suggestion_active_text ..

You have one div with a background image. inside this div do it

 <div style="text-align:center"> 1 </div> 

give a background image higher than

0
source

Add the following tags to both tags and it should do the trick:

 display: block; width:100px; 
0
source

Maybe a more modern answer?

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

Then use the flexbox div style as follows:

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

ALTERNATIVE for more dynamic positioning

set the background image div to

  positiion: relative; 

And your text block div to include

  position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); 
  • This allows you to move text, for example, 20% from the top instead of 50%.
  • translate (-50%, -50%) changes the alignment of the text element div to the center, which will be noticeable if you have longer text.
0
source

I think Flex works better, you can center it in both directions.

 suggestion_active { background-image:url(https://placeimg.com/120/120/tech/sepia); background-repeat:no-repeat; width: 100px; height: 36px; display: flex; justify-content: center; //horizontal alignment align-items: center; //vertical alignment } 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; } 
0
source

All Articles