Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a single character both vertically and horizontally in a square div

Tags:

I want to center within a square div an arbitrary character. I admit that this sounds like a very simple task, but nothing I've tried works (and I've tried a bazillion things!)1.

For concreteness, let's say that the div has height and width equal to 20ex, and let's say that the single character is the so-called "multiplication sign": ✕, nice and symmetric. I want this character to be positioned inside the 20ex-by-20ex square div such that the point where the two strokes cross is dead-center, both vertically and horizontally, within the div.

EDIT:

I tried the answers I've received so far, here. The solutions given by Jedidiah and by Ashok Kumar Gupta (second and third divs) produce pretty similar results, but (maybe I'm seeing things), the ✕ in the third div is just a hair above the vertical center.


1I have learned that no matter how mind-numbingly straightforward a layout task may appear, it can still take me hours and hours and hours to figure out the CSS to achieve it.

like image 408
kjo Avatar asked Nov 23 '13 19:11

kjo


People also ask

How do you center a div both vertically and horizontally?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do you center text horizontally and vertically?

Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center. In the Apply to box, click Selected text, and then click OK.

How do you center something vertically and horizontally?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How do I center a single div?

If it is a block element (a div is), you need to set margin: 0 auto; , else if it is an inline element, you need to set the text-align: center; on its parent element instead.


2 Answers

Setting the line-height to the height of the container should do it.

text-align: center;
line-height:20px;
width:20px;
height:20px;

Example here: http://codepen.io/Jedidiah/pen/rLfHz

like image 134
Jedidiah Avatar answered Oct 04 '22 15:10

Jedidiah


Use display:table-cell and vertical-align:middle and text-align:center. Like this in your CSS:

#center{
    width:100px;height:100px;
    display:table-cell;
    text-align:center;
    vertical-align:middle;
}

The display:table-cell is required to be able to use vertical-align to center content in the on the div ( don't ask me why someone decided to make it like that :) ).

See this JSFiddle.

like image 42
Robbie Wxyz Avatar answered Oct 04 '22 14:10

Robbie Wxyz