I have a div 200 x 200 px. I want to place a 50 x 50 px image right in the middle of the div.
How can it be done?
I am able to get it centered horizontally by using text-align: center
for the div. But vertical alignment is the issue..
I have a div 200 x 200 px. I want to place a 50 x 50 px image right in the middle of the div.
How can it be done?
I am able to get it centered horizontally by using text-align: center
for the div. But vertical alignment is the issue..
another way is to create a
table
withvalign
, of course. This would work regardless of you knowing the div's height or not.but you should always stick to just
css
whenever possible.This is coming a bit late, but here's a solution I use to vertical align elements within a parent div.
This is useful for when you know the size of the container div, but not that of the contained image. (this is frequently the case when working with lightboxes or image carousels).
Here's the styling you should try:
Use Flexbox :https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties
Personally, I'd place it as the background image within the div, the CSS for that being:
(Assumes a div with
id="demo"
as you are already specifyingheight
andwidth
adding abackground
shouldn't be an issue)Let the browser take the strain.
This works correctly:
else try this if the above only gives you horizontal centering:
here's another method to center everything within anything.
Working Fiddle
HTML: (simple as ever)
CSS:
Benefits
The Container and Content height are unknown.
Centering without specific negative margin, without setting the line-height (so it works well with multiple line of text) and without a script, also Works great with CSS transitions.