Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning HTML elements to the middle of the parent without JavaScript

Tags:

html

css

I want to place a <div> in the middle of an element. Aligning it horizontally is easy, and of course the vertical alignment can be done with JS, but I'm sure that there's a better way of doing this with CSS. What's the trick?

P.S. I need this for an application with the HTML5 <canvas> element, so I don't mind if the solution only works in browsers that support canvas and in IE 7,8 (which support canvas when using a plugin).


edit: the height (and width) of the div are resizable in browsers that support the CSS3 property resize. However, I don't mind about it too much.

another edit: I also don't know the height of the div (even if it hasn't been resized).


edit: see live demo here

this example uses JS. (Loktar - thanks for the link).


Thanks();

like image 806
string QNA Avatar asked Jan 28 '26 17:01

string QNA


1 Answers

Live Demo

One way to align vertically is to set the line-height to the height of the container.

#parent{
   width: 200px;
   height: 300px;
   line-height: 300px; 
   text-align:center;
}
like image 136
Loktar Avatar answered Jan 31 '26 06:01

Loktar