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.
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.
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.
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With