Related
So I know we can center a div horizontally if we use margin:0 auto;. Should margin:auto auto; work how I think it should work? Centering it vertically as well?
Why doesn't vertical-align:middle; work either?
.black {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
background:rgba(0,0,0,.5);
}
.message {
background:yellow;
width:200px;
margin:auto auto;
padding:10px;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
JSFiddle
Update Aug 2020
Although the below is still worth reading for the useful info, we have had Flexbox for some time now, so just use that, as per this answer.
You can't use:
vertical-align:middle because it's not applicable to block-level elements
margin-top:auto and margin-bottom:auto because their used values would compute as zero
margin-top:-50% because percentage-based margin values are calculated relative to the width of containing block
In fact, the nature of document flow and element height calculation algorithms make it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.
You can use:
A few workarounds like this which work for your scenario; the three elements have to be nested like so:
.container {
display: table;
height: 100%;
position: absolute;
overflow: hidden;
width: 100%;
}
.helper {
#position: absolute;
#top: 50%;
display: table-cell;
vertical-align: middle;
}
.content {
#position: relative;
#top: -50%;
margin: 0 auto;
width: 200px;
border: 1px solid orange;
}
<div class="container">
<div class="helper">
<div class="content">
<p>stuff</p>
</div>
</div>
</div
JSFiddle works fine according to Browsershot.
Since this question was asked in 2012 and we have come a long way with browser support for flexboxes, I felt as though this answer was obligatory.
If the display of your parent container is flex, then yes, margin: auto auto (also known as margin: auto) will work to center it both horizontally and vertically, regardless if it is an inline or block element.
#parent {
width: 50vw;
height: 50vh;
background-color: gray;
display: flex;
}
#child {
margin: auto auto;
}
<div id="parent">
<div id="child">hello world</div>
</div>
Note that the width/height do not have to be specified absolutely, as in this example jfiddle which uses sizing relative to the viewport.
Although browser support for flexboxes is at an all-time high at time of posting, many browsers still do not support it or require vendor prefixes. Refer to http://caniuse.com/flexbox for updated browser support information.
Update
Since this answer received a bit of attention, I would also like to point out that you don't need to specify margin at all if you're using display: flex and would like to center all of the elements in the container:
#parent {
width: 50vw;
height: 50vh;
background-color: gray;
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
}
<div id="parent">
<div>hello world</div>
</div>
Here's the best solution I've found: http://jsfiddle.net/yWnZ2/446/ Works in Chrome, Firefox, Safari, IE8-11 & Edge.
If you have a declared height (height: 1em, height: 50%, etc.) or it's an element where the browser knows the height (img, svg, or canvas for example), then all you need for vertical centering is this:
.message {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
margin: auto;
}
You'll usually want to specify a width or max-width so the content doesn't stretch the whole length of the screen/container.
If you're using this for a modal that you want always centered in the viewport overlapping other content, use position: fixed; for both elements instead of position: absolute. http://jsfiddle.net/yWnZ2/445/
Here's a more complete writeup: http://codepen.io/shshaw/pen/gEiDt
Edit: it's 2020, I would use flex box instead.
Original answer:
Html
<body>
<div class="centered">
</div>
</body>
CSS
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
I know the question is from 2012, but I found the easiest way ever, and I wanted to share.
HTML:
<div id="parent">
<div id="child">Content here</div>
</div>
and CSS:
#parent{
height: 100%;
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
If you know the height of the div you want to center, you can position it absolutely within its parent and then set the top value to 50%. That will put the top of the child div 50% of the way down its parent, i.e. too low. Pull it back up by setting its margin-top to half its height. So now you have the vertical midpoint of the child div sitting at the vertical midpoint of the parent - vertically centered!
Example:
.black {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
background:rgba(0,0,0,.5);
}
.message {
background:yellow;
width:200px;
margin:auto auto;
padding:10px;
position: absolute;
top: 50%;
margin-top: -25px;
height: 50px;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
http://jsfiddle.net/yWnZ2/2/
Those two solution require only two nested elements.
First - Relative and absolute positioning if the content is static (manual center).
.black {
position:relative;
min-height:500px;
background:rgba(0,0,0,.5);
}
.message {
position:absolute;
margin: 0 auto;
width: 180px;
top: 45%; bottom:45%; left: 0%; right: 0%;
}
https://jsfiddle.net/GlupiJas/5mv3j171/
or for fluid design - for exact content center use below example instead:
.message {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
https://jsfiddle.net/GlupiJas/w3jnjuv0/
You need 'min-height' set in case the content will exceed 50% of window height. You can also manipulate this height with media query for mobile and tablet devices . But only if You play with responsive design.
I guess You could go further and use simple JavaScript/JQuery script to manipulate the min-height or fixed height if there is a need for some reason.
Second - if content is fluid u can also use table and table-cell css properties with vertical alignment and text-align centered:
/*in a wrapper*/
display:table;
and
/*in the element inside the wrapper*/
display:table-cell;
vertical-align: middle;
text-align: center;
Works and scale perfectly, often used as responsive web design solution with grid layouts and media query that manipulate the width of the object.
.black {
display:table;
height:500px;
width:100%;
background:rgba(0,0,0,.5);
}
.message {
display:table-cell;
vertical-align: middle;
text-align: center;
}
https://jsfiddle.net/GlupiJas/4daf2v36/
I prefer table solution for exact content centering, but in some cases relative absolute positioning will do better job especially if we don't want to keep exact proportion of content alignment.
.black {
display:flex;
flex-direction: column;
height: 200px;
background:grey
}
.message {
background:yellow;
width:200px;
padding:10px;
margin: auto auto;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
There isn't one easy way to center div vertically which would do the trick in every situation.
However, there are lots of ways to do it depending on the situation.
Here are few of them:
Set top and bottom padding of the parent element for example padding:20px 0px 20px 0px
Use table, table cell centers its' content vertically
Set parent element's position relative and the div's you want to vertically center to absolute and style it as top:50px; bottom:50px; for example
You may also google for "css vertical centering"
variable height ,margin top and bottom auto
.black {background:rgba(0,0,0,.5);
width: 300px;
height: 100px;
display: -webkit-flex; /* Safari */
display: flex;}
.message{
background:tomato;
margin:auto;
padding:5%;
width:auto;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
variable height ,margin top and bottom auto
Using Flexbox:
HTML:
<div class="container">
<img src="http://lorempixel.com/400/200" />
</div>
CSS:
.container {
height: 500px;
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
}
View result
I think you can fix that with Flexbox
.black {
height : 200px;
width : 200px;
background-color : teal;
border: 5px solid rgb(0, 53, 53);
/* This is the important part */
display : flex;
justify-content: center;
align-items: center;
}
.message {
background-color : rgb(119, 128, 0);
border: 5px solid rgb(0, 53, 53);
height : 50%;
width : 50%;
padding : 5px;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
.black {
position:absolute;
/*
Replace with a one line inset property.
top:0;
bottom:0;
left:0;
right:0;
*/
inset: 0;
background:rgba(0,0,0,.5);
/*
Since no one has mentioned it yet,
here it is the grid display and
the place-content property.
*/
display:grid;
place-content: center;
}
.message {
background:yellow;
width:200px;
/*
There's no point here.
margin:auto auto;
*/
padding:10px;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
<div style="display:flex">
<img src="" style="display:block !important; margin:auto">
</div>
To center an image in a div horizontally and vertically
.black {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
background:rgba(0,0,0,.5);
}
.message {
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%, -50%);
background:yellow;
width:200px;
padding:10px;
}
-
----------
<div class="black">
<div class="message">
This is a popup message.
</div>
So I know we can center a div horizontally if we use margin:0 auto;. Should margin:auto auto; work how I think it should work? Centering it vertically as well?
Why doesn't vertical-align:middle; work either?
.black {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
background:rgba(0,0,0,.5);
}
.message {
background:yellow;
width:200px;
margin:auto auto;
padding:10px;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
JSFiddle
Update Aug 2020
Although the below is still worth reading for the useful info, we have had Flexbox for some time now, so just use that, as per this answer.
You can't use:
vertical-align:middle because it's not applicable to block-level elements
margin-top:auto and margin-bottom:auto because their used values would compute as zero
margin-top:-50% because percentage-based margin values are calculated relative to the width of containing block
In fact, the nature of document flow and element height calculation algorithms make it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.
You can use:
A few workarounds like this which work for your scenario; the three elements have to be nested like so:
.container {
display: table;
height: 100%;
position: absolute;
overflow: hidden;
width: 100%;
}
.helper {
#position: absolute;
#top: 50%;
display: table-cell;
vertical-align: middle;
}
.content {
#position: relative;
#top: -50%;
margin: 0 auto;
width: 200px;
border: 1px solid orange;
}
<div class="container">
<div class="helper">
<div class="content">
<p>stuff</p>
</div>
</div>
</div
JSFiddle works fine according to Browsershot.
Since this question was asked in 2012 and we have come a long way with browser support for flexboxes, I felt as though this answer was obligatory.
If the display of your parent container is flex, then yes, margin: auto auto (also known as margin: auto) will work to center it both horizontally and vertically, regardless if it is an inline or block element.
#parent {
width: 50vw;
height: 50vh;
background-color: gray;
display: flex;
}
#child {
margin: auto auto;
}
<div id="parent">
<div id="child">hello world</div>
</div>
Note that the width/height do not have to be specified absolutely, as in this example jfiddle which uses sizing relative to the viewport.
Although browser support for flexboxes is at an all-time high at time of posting, many browsers still do not support it or require vendor prefixes. Refer to http://caniuse.com/flexbox for updated browser support information.
Update
Since this answer received a bit of attention, I would also like to point out that you don't need to specify margin at all if you're using display: flex and would like to center all of the elements in the container:
#parent {
width: 50vw;
height: 50vh;
background-color: gray;
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
}
<div id="parent">
<div>hello world</div>
</div>
Here's the best solution I've found: http://jsfiddle.net/yWnZ2/446/ Works in Chrome, Firefox, Safari, IE8-11 & Edge.
If you have a declared height (height: 1em, height: 50%, etc.) or it's an element where the browser knows the height (img, svg, or canvas for example), then all you need for vertical centering is this:
.message {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
margin: auto;
}
You'll usually want to specify a width or max-width so the content doesn't stretch the whole length of the screen/container.
If you're using this for a modal that you want always centered in the viewport overlapping other content, use position: fixed; for both elements instead of position: absolute. http://jsfiddle.net/yWnZ2/445/
Here's a more complete writeup: http://codepen.io/shshaw/pen/gEiDt
Edit: it's 2020, I would use flex box instead.
Original answer:
Html
<body>
<div class="centered">
</div>
</body>
CSS
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
I know the question is from 2012, but I found the easiest way ever, and I wanted to share.
HTML:
<div id="parent">
<div id="child">Content here</div>
</div>
and CSS:
#parent{
height: 100%;
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
If you know the height of the div you want to center, you can position it absolutely within its parent and then set the top value to 50%. That will put the top of the child div 50% of the way down its parent, i.e. too low. Pull it back up by setting its margin-top to half its height. So now you have the vertical midpoint of the child div sitting at the vertical midpoint of the parent - vertically centered!
Example:
.black {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
background:rgba(0,0,0,.5);
}
.message {
background:yellow;
width:200px;
margin:auto auto;
padding:10px;
position: absolute;
top: 50%;
margin-top: -25px;
height: 50px;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
http://jsfiddle.net/yWnZ2/2/
Those two solution require only two nested elements.
First - Relative and absolute positioning if the content is static (manual center).
.black {
position:relative;
min-height:500px;
background:rgba(0,0,0,.5);
}
.message {
position:absolute;
margin: 0 auto;
width: 180px;
top: 45%; bottom:45%; left: 0%; right: 0%;
}
https://jsfiddle.net/GlupiJas/5mv3j171/
or for fluid design - for exact content center use below example instead:
.message {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
https://jsfiddle.net/GlupiJas/w3jnjuv0/
You need 'min-height' set in case the content will exceed 50% of window height. You can also manipulate this height with media query for mobile and tablet devices . But only if You play with responsive design.
I guess You could go further and use simple JavaScript/JQuery script to manipulate the min-height or fixed height if there is a need for some reason.
Second - if content is fluid u can also use table and table-cell css properties with vertical alignment and text-align centered:
/*in a wrapper*/
display:table;
and
/*in the element inside the wrapper*/
display:table-cell;
vertical-align: middle;
text-align: center;
Works and scale perfectly, often used as responsive web design solution with grid layouts and media query that manipulate the width of the object.
.black {
display:table;
height:500px;
width:100%;
background:rgba(0,0,0,.5);
}
.message {
display:table-cell;
vertical-align: middle;
text-align: center;
}
https://jsfiddle.net/GlupiJas/4daf2v36/
I prefer table solution for exact content centering, but in some cases relative absolute positioning will do better job especially if we don't want to keep exact proportion of content alignment.
.black {
display:flex;
flex-direction: column;
height: 200px;
background:grey
}
.message {
background:yellow;
width:200px;
padding:10px;
margin: auto auto;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
There isn't one easy way to center div vertically which would do the trick in every situation.
However, there are lots of ways to do it depending on the situation.
Here are few of them:
Set top and bottom padding of the parent element for example padding:20px 0px 20px 0px
Use table, table cell centers its' content vertically
Set parent element's position relative and the div's you want to vertically center to absolute and style it as top:50px; bottom:50px; for example
You may also google for "css vertical centering"
variable height ,margin top and bottom auto
.black {background:rgba(0,0,0,.5);
width: 300px;
height: 100px;
display: -webkit-flex; /* Safari */
display: flex;}
.message{
background:tomato;
margin:auto;
padding:5%;
width:auto;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
variable height ,margin top and bottom auto
Using Flexbox:
HTML:
<div class="container">
<img src="http://lorempixel.com/400/200" />
</div>
CSS:
.container {
height: 500px;
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
}
View result
I think you can fix that with Flexbox
.black {
height : 200px;
width : 200px;
background-color : teal;
border: 5px solid rgb(0, 53, 53);
/* This is the important part */
display : flex;
justify-content: center;
align-items: center;
}
.message {
background-color : rgb(119, 128, 0);
border: 5px solid rgb(0, 53, 53);
height : 50%;
width : 50%;
padding : 5px;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
.black {
position:absolute;
/*
Replace with a one line inset property.
top:0;
bottom:0;
left:0;
right:0;
*/
inset: 0;
background:rgba(0,0,0,.5);
/*
Since no one has mentioned it yet,
here it is the grid display and
the place-content property.
*/
display:grid;
place-content: center;
}
.message {
background:yellow;
width:200px;
/*
There's no point here.
margin:auto auto;
*/
padding:10px;
}
<div class="black">
<div class="message">
This is a popup message.
</div>
</div>
<div style="display:flex">
<img src="" style="display:block !important; margin:auto">
</div>
To center an image in a div horizontally and vertically
.black {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
background:rgba(0,0,0,.5);
}
.message {
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%, -50%);
background:yellow;
width:200px;
padding:10px;
}
-
----------
<div class="black">
<div class="message">
This is a popup message.
</div>
I have an image of 400px and a div that is smaller (the width is not always 300px as in my example). I want to center the image in the div, and if there is an overflow, hide it.
Note: I must keep the position:absolute on the image. I'm working with css-transitions, and if I use position:relative, my image shakes a bit (https://web.archive.org/web/20120528225923/http://ta6.maxplus.be:8888/).
jsfiddle
http://jsfiddle.net/wjw83/1/
You should make the container relative and give it a height as well and you're done.
http://jsfiddle.net/jaap/wjw83/4/
.main {
width: 300px;
margin: 0 auto;
overflow: hidden;
position: relative;
height: 200px;
}
img.absolute {
left: 50%;
margin-left: -200px;
position: absolute;
}
<div class="main">
<img class="absolute" src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />
</div>
<br />
<img src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />
If you want to you can also center the image vertically by adding a negative margin and top position: http://jsfiddle.net/jaap/wjw83/5/
None of the above solutions were working out well for me. I needed a dynamic image size to fit in a circular parent container with overflow:hidden
.circle-container {
width:100px;
height:100px;
text-align:center;
border-radius:50%;
overflow:hidden;
}
.circle-img img {
min-width:100px;
max-width:none;
height:100px;
margin:0 -100%;
}
Working example here:
http://codepen.io/simgooder/pen/yNmXer
Most recent solution:
HTML
<div class="parent">
<img src="image.jpg" height="600" width="600"/>
</div>
CSS
.parent {
width: 200px;
height: 200px;
overflow: hidden;
/* Magic */
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
}
Found this nice solution by MELISSA PENTA (https://www.localwisdom.com/)
HTML
<div class="wrapper">
<img src="image.jpg" />
</div>
CSS
div.wrapper {
height:200px;
line-height:200px;
overflow:hidden;
text-align:center;
width:200px;
}
div.wrapper img {
margin:-100%;
}
Center any size image in div
Used with rounded wrapper and different sized images.
CSS
.item-image {
border: 5px solid #ccc;
border-radius: 100%;
margin: 0 auto;
height: 200px;
width: 200px;
overflow: hidden;
text-align: center;
}
.item-image img {
height: 200px;
margin: -100%;
max-width: none;
width: auto;
}
Working example here codepen
For me flex-box worked perfect to center the image.
this is my html-code:
<div class="img-wrapper">
<img src="..." >
</div>
and this i used for css:
I wanted the Image same wide as the wrapper-element, but if the height is greater than the height of the wrapper-element it should be "cropped"/not displayed.
.img-wrapper{
width: 100%;
height: 50%;
overflow: hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
img {
height: auto;
width: 100%;
}
working solution with flex-box for posterity:
main points:
overflow hidden for wrapper
image height and width must be specified, cannot be percentage.
use any method you want to center the image.
wrapper {
width: 80;
height: 80;
overflow: hidden;
align-items: center;
justify-content: center;
}
image {
width: min-content;
height: min-content;
}
<html>
<head>
<style type="text/css">
.div-main{
height:200px;
width:200px;
overflow: hidden;
background:url(img.jpg) no-repeat center center
}
</style>
</head>
<body>
<div class="div-main">
</div>
</body>
just make sure how you are using image through css background use backgroud image position like background: url(your image path) no-repeat center center; automatically it wil align center to the screen.
this seems to work on our site, using your ideas and a little math based upon the left edge of wrapper div. It seems redundant to go left 50% then take out 50% extra margin, but it seems to work.
div.ImgWrapper {
width: 160px;
height: 160px
overflow: hidden;
text-align: center;
}
img.CropCenter {
left: 50%;
margin-left: -100%;
position: relative;
width: auto !important;
height: 160px !important;
}
<div class="ImgWrapper">
<img class="CropCenter" src="img.png">
</div>
I have been trying to implement Jaap's answer inside this page of my recent site, with one difference : the .main {height:} was set to auto instead of a fixed px value.
As responsive developer i am looking for a solution to synchronize the image height with the left floating text element, yet only in case my text height becomes greater then my actual image height.
In that case the image should not be rescaled, but cropped and centered as decribed in the original question here above.
Can this be done ?
You can simulate the behaviour by slowly downsizing the browser's width.
This issue is a huge pain in the a.. but I finally got it.
I've seen a lot of complicated solutions. This is so simple now that I see it.
.parent {
width:70px;
height:70px;
}
.child {
height:100%;
width:10000px; /* Or some other impossibly large number */
margin-left: -4965px; /* -1*((child width-parent width)/2) */
}
.child img {
display:block; /* won't work without this */
height:100%;
margin:0 auto;
}
you the have to corp your image from sides to hide it try this
3 Easy and Fast CSS Techniques for Faux Image Cropping | Css ...
one of the demo for the first way on the site above
try demo
i will do some reading on it too
I have a container div with a floating left-hand navigation pane and a content pane to the right:
<div id="header"></div>
<div id="container">
<div id="leftnav"></div>
<div id="content"></div>
<div class="clearfix"></div>
</div>
<div id="footer"></div>
CSS:
body
{
text-align: center; /* IE center div fix */
}
#container
{
width: 800px; /* site width */
background-color: red; /* so I can see it */
text-align: left; /* undo text-align: center; */
margin: 0 auto; /* standards-compliant centering */
}
#leftnav
{
float: left;
width: 200px;
}
#content
{
height: 100%;
width: 600px;
margin-left: 200px;
background-color: green; /* so I can see it */
}
.clearfix { clear: both; }
The #container div stretches to the full height of the floating #leftnav div, but the contained #content div does not stretch to 100% of the height. I've read elsewhere that this is due to the parent #container not having a specified height (defaults to auto) and therefore the 100% is not based on that container; however, I can't specify the height because the left navigation pane height isn't constant.
How can I get the #content div to be 100% of the height of the #container div when the #container div's height is defined by the floating #leftnav?
This is similar to the 3 column liquid "holy grail" CSS layout that has been plaguing people for years (though has been solved in the past couple years, though many of the solutions required browser hacks or Javascript to function).
I'd highly suggest you not reinvent the wheel here as it is difficult to get CSS to perform exactly as you're describing. Here is a good resource for this layout and many other similar liquid layouts:
http://matthewjamestaylor.com/blog/perfect-2-column-left-menu.htm
The easy way would be to use JS to set the height of #content to the height of #leftnav. You can use faux columns on #container and make a slice/gif of the green background and repeat it vertically on #container along with the red however you have it but I'm not sure if it fits your needs.
try this CSS
body
{
text-align: center; /* IE center div fix */
}
#container
{
width: 800px; /* site width */
background-color: red; /* so I can see it */
text-align: left; /* undo text-align: center; */
margin: 0 auto; /* standards-compliant centering */
}
#leftnav
{
float: left;
width: 200px;
}
#content
{
height: 100%;
width: 600px;
background-color: green; /* so I can see it */
float:right;
}
.clearfix { clear: both; }
I would also suggest using a line break with a clear both rather than a div.
This question already has answers here:
How to vertically align an image inside a div
(37 answers)
Flexbox: center horizontally and vertically
(14 answers)
How can I vertically align elements in a div?
(28 answers)
How do I center an image if it's wider than its container?
(10 answers)
Closed 3 years ago.
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..
Working in old browsers (IE >= 8)
Absolute position in combination with automatic margin permits to center an element horizontally and vertically. The element position could be based on a parent element position using relative positioning. View Result
img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
Personally, I'd place it as the background image within the div, the CSS for that being:
#demo {
background: url(bg_apple_little.gif) no-repeat center center;
height: 200px;
width: 200px;
}
(Assumes a div with id="demo" as you are already specifying height and width adding a background shouldn't be an issue)
Let the browser take the strain.
another way is to create a table with valign, of course. This would work regardless of you knowing the div's height or not.
<div>
<table width="100%" height="100%" align="center" valign="center">
<tr><td>
<img src="foo.jpg" alt="foo" />
</td></tr>
</table>
</div>
but you should always stick to just css whenever possible.
I would set your larger div with position:relative; then for your image do this:
img.classname{
position:absolute;
top:50%;
left:50%;
margin-top:-25px;
margin-left:-25px;
}
This only works because you know the dimensions of both the image and the containing div. This will also let you have other items within the containing div... where solutions like using line-height will not.
EDIT: Note... your margins are negative half of the size of the image.
This works correctly:
display: block;
margin-left: auto;
margin-right: auto
else try this if the above only gives you horizontal centering:
.outerContainer {
position: relative;
}
.innerContainer {
width: 50px; //your image/element width here
height: 50px; //your image/element height here
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
Use Flexbox:
.outerDiv {
display: flex;
flex-direction: column;
justify-content: center; /* Centering y-axis */
align-items :center; /* Centering x-axis */
}
here's another method to center everything within anything.
Working Fiddle
HTML: (simple as ever)
<div class="Container">
<div class="Content"> /*this can be an img, span, or everything else*/
I'm the Content
</div>
</div>
CSS:
.Container
{
text-align: center;
}
.Container:before
{
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
.Content
{
display: inline-block;
vertical-align: middle;
}
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.
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:
container div
{
display:table-cell;
vertical-align:middle;
height:200px;
width:200px;
}
img
{
/*Apply any styling here*/
}
I've found that Valamas' and Lepu's answers above are the most straightforward answers that deal with images of unknown size, or of known size that you'd rather not hard-code into your CSS. I just have a few small tweaks: remove irrelevant styles, size it to 200px to match the question, and add max-height/max-width to handle images that may be too large.
div.image-thumbnail
{
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
}
div.image-thumbnail img
{
vertical-align: middle;
max-height: 200px;
max-width: 200px;
}
in the div
style="text-align:center; line-height:200px"
We can easily achieve this using flex. no need for background-image.
<!DOCTYPE html>
<html>
<head>
<style>
#image-wrapper{
width:500px;
height:500px;
border:1px solid #333;
display:flex;
justify-content:center;
align-items:center;
}
</style>
</head>
<body>
<div id="image-wrapper">
<img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">
</div>
</body>
</html>
Vertical-align is one of the most misused css styles. It doesn't work how you might expect on elements that are not td's or css "display: table-cell".
This is a very good post on the matter. http://phrogz.net/CSS/vertical-align/index.html
The most common methods to acheive what you're looking for are:
padding top/bottom
position absolute
line-height
In CSS do it as:
img
{
display:table-cell;
vertical-align:middle;
margin:auto;
}
#sleepy You can easily do this using the following attributes:
#content {
display: flex;
align-items: center;
width: 200px;
height: 200px;
border: 1px solid red;
}
#myImage {
display: block;
width: 50px;
height: 50px;
margin: auto;
border: 1px solid yellow;
}
<div id="content">
<img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">
</div>
References: W3
Typically, I'll set the line-height to be 200px. Usually does the trick.
I have a gallery of images for which I don't know the exact heights or widths of images beforhand, I just know that they are smaller than the div in which they are going to be contained.
By doing a combination of line-height settings on the container and using vertical-align:middle on the image element, I finally got it to work on FF 3.5, Safari 4.0 and IE7.0 using the following HTML markup and the following CSS.
The HTML Markup
<div id="gallery">
<div class="painting">
<a href="Painting/Details/2">
<img src="/Content/Images/Paintings/Thumbnail/painting_00002.jpg" />
</a>
</div>
<div class="painting">
...
</div>
...
</div>
The CSS
div.painting
{
float:left;
height:138px; /* fixed dimensions */
width: 138px;
border: solid 1px white;
background-color:#F5F5F5;
line-height:138px;
text-align:center;
}
div.painting a img
{
border:none;
vertical-align:middle;
}
This works for me :
<body>
<table id="table-foo">
<tr><td>
<img src="foo.png" />
</td></tr>
</table>
</body>
<style type="text/css">
html, body {
height: 100%;
}
#table-foo {
width: 100%;
height: 100%;
text-align: center;
vertical-align: middle;
}
#table-foo img {
display: block;
margin: 0 auto;
}
</style>
Another way (not mentioned here yet) is with Flexbox.
Just set the following rules on the container div:
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
FIDDLE
div {
width: 200px;
height: 200px;
border: 1px solid green;
display: flex;
justify-content: center;
/* align horizontal */
align-items: center;
/* align vertical */
}
<div>
<img src="http://lorempixel.com/50/50/food" alt="" />
</div>
A good place to start with Flexbox to see some of it's features and get syntax for maximum browser support is flexyboxes
Also, browser support nowadays is quite good: caniuse
For cross-browser compatibility for display: flex and align-items, you can use the following:
display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
This is an old solution but browser market shares have advanced enough that you may be able to get by without the IE hack part of it if you are not concerned about degrading for IE7. This works when you know the dimensions of the outer container but may or may not know the dimensions of the inner image.
.parent {
display: table;
height: 200px; /* can be percentages, too, like 100% */
width: 200px; /* can be percentages, too, like 100% */
}
.child {
display: table-cell;
vertical-align: middle;
margin: 0 auto;
}
<div class="parent">
<div class="child">
<img src="foo.png" alt="bar" />
</div>
</div>
easy
img {
transform: translate(50%,50%);
}
You can set position of image is align center horizontal by this
#imageId {
display: block;
margin-left: auto;
margin-right:auto;
}
I've been trying to get an image to be centered vertically and horizontally within a circle shape using hmtl and css.
After combining several points from this thread, here's what I came up with: jsFiddle
Here's another example of this within a three column layout: jsFiddle
CSS:
#circle {
width: 100px;
height: 100px;
background: #A7A9AB;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
margin: 0 auto;
position: relative;
}
.images {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
HTML:
<div id="circle">
<img class="images" src="https://png.icons8.com/facebook-like-filled/ios7/50" />
</div>
You can center an image horizontally and vertically with the code below (works in IE/FF).
It will put the top edge of the image at exactly 50% of the browser height, and the margin-top(pulling half the height of the image up) will center it perfectly.
<style type="text/css">
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {vertical-align: middle; width: 100%;}
#inner {position: relative; top: -50%} /* for explorer only */
</style>
<body style="background-color:#eeeeee">
<div id="middle">
<div id="inner" align="center" style="margin-top:...px"> /* the number will be half the height of your image, so for example if the height is 500px then you will put 250px for the margin-top */
<img src="..." height="..." width="..." />
</div>
</div>
</body>
I love jumping on old bandwagons!
Here's a 2015 update to this answer. I started using CSS3 transform to do my dirty work for positioning. This allows you to not have to make any extra HTML, you don't have to do math (finding half-widths of things) you can use it on any element!
Here's an example (with fiddle at the end). Your HTML:
<div class="bigDiv">
<div class="smallDiv">
</div>
</div>
With accompanying CSS:
.bigDiv {
width:200px;
height:200px;
background-color:#efefef;
position:relative;
}
.smallDiv {
width:50px;
height:50px;
background-color:#cc0000;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
What I do a lot these days is I will give a class to things I want centered and just re-use that class every time. For example:
<div class="bigDiv">
<div class="smallDiv centerThis">
</div>
</div>
css
.bigDiv {
width:200px;
height:200px;
background-color:#efefef;
position:relative;
}
.smallDiv {
width:50px;
height:50px;
background-color:#cc0000;
}
.centerThis {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
This way, I will always be able to center something in it's container. You just have to make sure that the thing you want centered is in a container that has a position defined.
Here's a fiddle
BTW: This works for centering BIGGER divs inside SMALLER divs as well.
div {
position: absolute;
border: 3px solid green;
width: 200px;
height: 200px;
}
img {
position: relative;
border: 3px solid red;
width: 50px;
height: 50px;
}
.center {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%); /* IE 9 */
-webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */
}
<div class="center">
<img class="center" src="http://placeholders.org/250/000/fff" />
</div>
Related: Center a image
thanks to everyone else for the clues.
I used this method
div.image-thumbnail
{
width: 85px;
height: 85px;
line-height: 85px;
display: inline-block;
text-align: center;
}
div.image-thumbnail img
{
vertical-align: middle;
}
Use positioning. The following worked for me:
div{
display:block;
overflow:hidden;
width: 200px;
height: 200px;
position: relative;
}
div img{
width: 50px;
height: 50px;
top: 50%;
left: 50%;
bottom: 50%;
right: 50%;
position: absolute;
}
Simply set image margin auto as shown below.
img{
margin:auto;
width:50%;
height:auto;
}
Check these example
.container {
height: 200px;
width: 200px;
float:left;
position:relative;
}
.children-with-img {
position: absolute;
width:50px;
height:50px;
left:50%;
top:50%;
transform:translate(-50%);
}
If you know the size of the parent div and the image, you can just use absolute positioning.