0

I want to render some text in a DIV which should appear at the center of the SPAN - both vertically as well as horizontally.

This is my jsfiddle - http://jsfiddle.net/8Syqv/13/

HTML:

 <span>something here</span>

CSS:

body { height: 100%; width: 100%; }

span {
position: absolute;
border: 1px red solid;
height: 30%;
width: 40%;
text-align: center;
vertical-align: middle;
left: 0;
margin: auto;
top: 0;
right: 0;

}

I have looked at these:

Vertical and Horizontal alignment of text with CSS

How to center an element horizontally and vertically?

and more..

But, the ideas suggested here did not work on my jsfiddle. I think m missing something here. not sure what>

Thank You

Community
  • 1
  • 1
Cute_Ninja
  • 4,742
  • 4
  • 39
  • 63
  • Are you assuming you have to set the height of the element? Whether in px or percentage? – Blunderfest Jun 30 '14 at 17:38
  • does the span have to be `position: absolute;`? – Nico O Jun 30 '14 at 17:39
  • Percentage. This percentage is also being calculated on the fly based on the width and height of parent element and sibling elements. So, it is never fixed. – Cute_Ninja Jun 30 '14 at 17:39
  • No, actually it has position relative. But, I tried position absolute after looking at other jsfiddle examples in stackoverflow with similar problems. So, you can scratch that – Cute_Ninja Jun 30 '14 at 17:41
  • Why set a height if you want the content to be centered? Why not just give it a top and bottom padding and be done? http://jsfiddle.net/AWU77/ – Blunderfest Jun 30 '14 at 17:45

1 Answers1

2

This may changes the HTML you wrote your question around. But i guess, this will help you anyways:

DEMO: http://jsfiddle.net/8Syqv/39/

(altered) HTML

<div>
    <span>something here</span>
</div>

Some CSS

body 
{
    height: 100%;
    width: 100%; 
}

div
{
   border: 1px red solid;
   height: 30%;
   width: 40%;  
   text-align: center;
   left: 0;
   margin: auto;
   top: 0;
   right: 0;
   position: absolute;
}

span 
{  
    display: inline-block; 
    vertical-align: middle;
}

div:after
{
   display: inline-block; 
   vertical-align: middle; 
   height: 100%;
   content:"";
}
Nico O
  • 13,762
  • 9
  • 54
  • 69