28

I have a HTML code as;

<div class="left">
<span class="panelTitleTxt">Title text</span>
</div>

My CSS is as follows;

.left {
    background-color: #999999;
    height: 50px;
    width: 24.5%;
}
span.panelTitleTxt {
                display: block;
                width: 100%;
                height: 100%;
}

Now how do I center align the span text inside the div? (Assume that the "left" div after the % conversion gets a px width of 100px)

I tried the standard way of using margin:auto, but that is not working.

Also I want to avoid using text-align:center.

Is there some other way of fixing this?

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 7
    Why do you want to avoid "text-align:center" if you don't mind me asking? – Joey Ciechanowicz Oct 25 '11 at 08:23
  • If you want to center-align the span’s text, use `span {text-align:center;}`. If this doesn’t produce the output you want, you’re going to have to explain why for us to be able to help you. (Otherwise we just have to guess what your actual requirements are.) – Paul D. Waite Oct 25 '11 at 08:49
  • If it's a _title_, use the appropriate tag (h1, h2, h31 h4, h5 or h6), Don't use a non semantic . – Kyle Oct 25 '11 at 08:58
  • In case anyone wants to use *style="vertical-align: middle;"* ... it only works if you apply it to the container DIV. Applying it to the span does nothing... at least in IE10. – Jason Parker Jul 16 '13 at 19:16

2 Answers2

31

You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.

You could give the span a set width, then add the margin:0 auto again. This would center-align it.

.left 
{
   background-color: #999999;
   height: 50px;
   width: 24.5%;
}
span.panelTitleTxt 
{
   display:block;
   width:100px;
   height: 100%;
   margin: 0 auto;
}
Kyle
  • 65,599
  • 28
  • 144
  • 152
Lee
  • 5,816
  • 6
  • 45
  • 61
4

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

Emre
  • 831
  • 11
  • 13
Cuse70
  • 271
  • 3
  • 5