To center an HTML element I can use the CSS left: 50%;. However, this centers the element with respect to the whole window.
I have an element which is a child of a <div> element and I want to center the child with respect to this parent <div>, not the whole window.
I do not want the container <div> to have all its content centered, just the one specific child.
Set text-align:center; to the parent div, and margin:auto; to the child div.
#parent {
text-align:center;
background-color:blue;
height:400px;
width:600px;
}
.block {
height:100px;
width:200px;
text-align:left;
}
.center {
margin:auto;
background-color:green;
}
.left {
margin:auto auto auto 0;
background-color:red;
}
.right {
margin:auto 0 auto auto;
background-color:yellow;
}
<div id="parent">
<div id="child1" class="block center">
a block to align center and with text aligned left
</div>
<div id="child2" class="block left">
a block to align left and with text aligned left
</div>
<div id="child3" class="block right">
a block to align right and with text aligned left
</div>
</div>
This a good resource to center mostly anything.
http://howtocenterincss.com/
Actually this is very straightforward with CSS3 flex boxes.
.flex-container{
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex; /* NEW, Spec - Firefox, Chrome, Opera */
justify-content: center;
align-items: center;
width: 400px;
height: 200px;
background-color: #3498db;
}
.inner-element{
width: 100px;
height: 100px;
background-color: #f1c40f;
}
<div class="flex-container">
<div class="inner-element"></div>
</div>
UPDATE:
It seems that I didn't read the OP edit at the time I wrote this answer. The above code will center all inner elements (without overlapping between them), but the OP wants just an specific element to be centered, not the other inner elements. So #Warface answer second method is more appropiate, but it still requires vertical centering:
.flex-container{
position: relative;
/* Other styling stuff */
width: 400px;
height: 200px;
background-color: #3498db;
}
.inner-element{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
/* or 3d alternative if you will add animations (smoother transitions) */
transform: translate3d(-50%,-50%,0);
/* Other styling stuff */
width: 100px;
height: 100px;
background-color: #f1c40f;
}
<div class="flex-container">
<p>Other inner elements like this follows the normal flow.</p>
<div class="inner-element"></div>
</div>
CSS
body{
text-align:center;
}
.divWrapper{
width:960px //Change it the to width of the parent you want
margin: 0 auto;
text-align:left;
}
HTML
<div class="divWrapper">Tada!!</div>
This should center the div
2016 - HTML5 + CSS3 method
CSS
div#relative{
position:relative;
}
div#thisDiv{
position:absolute;
left:50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
}
HTML
<div id="relative">
<div id="thisDiv">Bla bla bla</div>
</div>
Fiddledlidle
https://jsfiddle.net/1z7m83dx/
You can use bootstrap flex class name like that:
<div class="d-flex justify-content-center">
// the elements you want to center
</div>
That will work even with number of elements inside.
To center only the specific child :
.parent {
height: 100px;
background-color: gray;
position: relative;
}
.child {
background-color: white;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 20px;
height:20px;
margin: auto;
}
<div class="parent">
<span class="child">hi</span>
</div>
OR, you can use flex too, but that would center all children
.parent {
height: 100px;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
}
.child {
background-color: white;
}
<div class="parent">
<span class="child">hi</span>
</div>
text-align:center; on the parent div Should do the trick
Is the div a fixed width or a fluid width? Either way, for fluid width you could use:
#element { /* this is the child div */
margin-left:auto;
margin-right:auto;
/* Add remaining styling here */
}
Or you could set the parent div to text-align:center; and the child div to text-align:left;.
And left:50%; only centers it according to the whole page when the div is set to position:absolute;. If yous set the div to left:50%; it should do it relative to the parent div's width. For fixed width, do this:
#parent {
width:500px;
}
#child {
left:50%;
margin-left:-100px;
width:200px;
}
just give the parent div position: relative
I believe the modern way to go is place-items: center in the parent container
An example can be found here: https://1linelayouts.glitch.me
If you want to use CSS3:
position:absolute;
left:calc(50% - PutTheSizeOfTheHalfOfYourElementpx);
You might want to do further searches to figure out how to get the percentage to fit your element's width.
after flex it show essay
.container{
display:flex;
color:blue;
background-color: yellow;
justify-content:center;
}
<div class="container">
<div>Element</div>
</div>
and if you set element Center elements horizontally and vertically.
.container{
display:flex;
color:blue;
height:100px;
background-color: yellow;
justify-content:center;
align-items:center;
}
<div class="container">
<div>Element</div>
</div>
First of all you can do it with left:50% to center it relative to parent div but for that you need to learn CSS positioning.
One possible solution from many is to do something like
div.parent { text-align:center; } //will center align every thing in this div as well as in the children element
div.parent div { text-align:left;} //to restore so every thing would start from left
if your your div to be centered is positioned relatively, you can just do
.mydiv { position:relative; margin:0 auto; }
left: 50% works resectively to the nearest parent with static width assigned. Try width: 500px or something on parent div. Alternatively, make the content you need to center display:block and set left and right margins to auto.
If the child element is inline (e.g not a div, table etc) I would wrap it up inside a div or a p and make the wrapper's text align css property equal to center.
<div id="container">
This text is aligned to the left.<br>
So is this text.<br>
<div style="text-align: center">
This <button>button</button> is centered.
</div>
This text is still aligned left.
</div>
Otherwise, if the element is a block (display: block, e.g a div or a p) with a fixed width, I'd set its margin left and right css properties to auto.
<div id="container">
This text is aligned to the left.<br>
So is this text.<br>
<div style="margin: 0 auto; width: 200px; background: red; color: white;">
My parent is centered.
</div>
This text is still aligned left.
</div>
You could of course add a text-align: center to the wrapper element to make its contents centered as well.
I won't bother with positioning because IMHO its not the way to go for the OPs problem but be sure to check this link out, very helpful.
Create a new div element for your element to center, then add a class specifically for centering that element like this
<div id="myNewElement">
<div class="centered">
<input type="button" value="My Centered Button"/>
</div>
</div>
Css
.centered{
text-align:center;
}
I have found another solution
<style type="text/css">
.container {
width:600px; //set how much you want
overflow: hidden;
position: relative;
}
.containerSecond{
position: absolute;
top:0px;
left:-500%;
width:1100%;
}
.content{
width: 800px; //your content size
margin:0 auto;
}
</style>
and in body
<div class="container">
<div class="containerSecond">
<div class="content"></div>
</div>
</div>
This will center your content div whenever your container is bigger or smaller. In this case your content should be bigger than 1100% of container to not be centered, but in that case you can make with of containerSecond bigger, and it will work
Assign text-align: center; to the parent and display: inline-block; to the div.
for example, i have an article div which is inside a main content div..
Inside the article theres an image and under that image is a button, style like this:
.article {
width: whatever;
text-align: center;
float: whatever (in case you got more articles in a row);
margin: give it whatever margin you want;
}
.article {
}
/* inside the article i want the image centered */
.article img {
float: none;
margin: 0 auto;
padding: give it a padded ridge if you want;
}
/* Now under this image in the same article element there should be a button like read more Of course you need to work with em or % when its inside a responsive design*/
.button {
background: #whatever color:
padding: 4.3567%; /*Instead of fixed width*/
text-align: cente;
font: whatever;
max-width: 41.4166%;
float: none;
margin: 0 auto; /* You could make the zero into any margin you want on the top and bottom of this button.. Just notice the float: none property.. this wil solve most your issues, also check if maybe position and displaay might mess up your code..*/
}
Good luck
If you want to center elements inside a div and don't care about division size you could use Flex power. I prefer using flex and don't use exact size for elements.
<div class="outer flex">
<div class="inner">
This is the inner Content
</div>
</div>
As you can see Outer div is Flex container and Inner must be Flex item that specified with flex: 1 1 auto; for better understand you could see this simple sample. http://jsfiddle.net/QMaster/hC223/
Hope this help.
mine would like magic.
html, body {
height: 100%;
}
.flex-container{
display: -ms-flexbox;
display: -webkit-box;
display: flex;
-ms-flex-align: center;
-ms-flex-pack: center;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: center;
justify-content: center;
}
<div class="flex-container">
<div>Content</div>
</div>
<html>
<head>
</head>
<style>
.out{
width:200px;
height:200px;
background-color:yellow;
}
.in{
width:100px;
height:100px;
background-color:green;
margin-top:50%;
margin-left:50%;
transform:translate(-50%,50%);
}
</style>
<body>
<div class="out">
<div class="in">
</div>
</div>
</body>
</html>
There can be a lot of ways on how you can center an element, it can be either using display properties or position or floats or margins. But normally I prefer using flexbox as it is easy and simple. I know that different people have different preferences but it depends entirely on the developer's preference and relation of the elements.
.parent{
display: block;
}
.sub-parent-1{
display: flex;
justify-content: center; //horizontal centering
align-items: center; //vertical centering
}
<body>
<div class="parent">
<div class="sub-parent-1">
<div class="child-1">...</div>
</div>
<div class="child-2">...</div>
<div class="child-3">...</div>
<div class="child-4">...</div>
<div class="child-5">...</div>
</div>
</body>
If none of those answers hit's it. Try this one.
Horizontally and vertically aligned child element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="content">
<img width="300px" src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Building92microsoft.jpg/800px-Building92microsoft.jpg" alt="microsoft" />
</div>
</div>
</body>
<style>
.container {
display: flex; /* can also use grid */
background-color: #47472d;
width: 500px;
height: 400px;
overflow: auto;
}
.content { margin: auto; }
</style>
</html>
Related
How can I horizontally center a <div> within another <div> using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
With flexbox it is very easy to style the div horizontally and vertically centered.
#inner {
border: 0.05em solid black;
}
#outer {
border: 0.05em solid red;
width:100%;
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
To align the div vertically centered, use the property align-items: center.
Other Solutions
You can apply this CSS to the inner <div>:
#inner {
width: 50%;
margin: 0 auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width.
Working example here:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
If you don't want to set a fixed width on the inner div you could do something like this:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
That makes the inner div into an inline element that can be centered with text-align.
The best approaches are with CSS3.
The old box model (deprecated)
display: box and its properties box-pack, box-align, box-orient, box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.
#outer {
width: 100%;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
#inner {
width: 50%;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
According to your usability you may also use the box-orient, box-flex, box-direction properties.
The modern box model with Flexbox
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
Read more about centering the child elements
CSS Box Model Module Level 3
Box model (CSS2)
box-align on MDN
And this explains why the box model is the best approach:
Why is the W3C box model considered better?
#centered {
position: absolute;
left: 50%;
margin-left: -100px;
}
<div id="outer" style="width:200px">
<div id="centered">Foo foo</div>
</div>
Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.
If you don't know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.
With CSS calc(), the code can get even simpler:
.centered {
width: 200px;
position: absolute;
left: calc(50% - 100px);
}
The principle is still the same; put the item in the middle and compensate for the width.
I've created this example to show how to vertically and horizontally align.
The code is basically this:
#outer {
position: relative;
}
and...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
And it will stay in the center even when you resize your screen.
Some posters have mentioned the CSS 3 way to center using display:box.
This syntax is outdated and shouldn't be used anymore. [See also this post].
So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module.
So if you have simple markup like:
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...and you want to center your items within the box, here's what you need on the parent element (.box):
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box {
display: flex;
flex-wrap: wrap;
/* Optional. only if you want the items to wrap */
justify-content: center;
/* For horizontal alignment */
align-items: center;
/* For vertical alignment */
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
.box {
height: 200px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border: 2px solid tomato;
}
.box div {
margin: 0 10px;
width: 100px;
}
.item1 {
height: 50px;
background: pink;
}
.item2 {
background: brown;
height: 100px;
}
.item3 {
height: 150px;
background: orange;
}
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
If you need to support older browsers which use older syntax for flexbox here's a good place to look.
If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.
You can use:
#element {
display: table;
margin: 0 auto;
}
Centering a div of unknown height and width
Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)
.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>
Tinker with it further on Codepen or on JSBin.
Set the width and set margin-left and margin-right to auto. That's for horizontal only, though. If you want both ways, you'd just do it both ways. Don't be afraid to experiment; it's not like you'll break anything.
It cannot be centered if you don't give it a width. Otherwise, it will take, by default, the whole horizontal space.
CSS 3's box-align property
#outer {
width: 100%;
height: 100%;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
The way I usually do it is using absolute position:
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
The outer div doesn't need any extra properties for this to work.
I recently had to center a "hidden" div (i.e., display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn't necessary to display.)
NOTE: I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and can't be resized/centered until after they are displayed.
$(function(){
$('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inner" style="display:none;">
<form action="">
<table id="innerTable">
<tr><td>Name:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="submit"></td></tr>
</table>
</form>
</div>
For Firefox and Chrome:
<div style="width:100%;">
<div style="width: 50%; margin: 0px auto;">Text</div>
</div>
For Internet Explorer, Firefox, and Chrome:
<div style="width:100%; text-align:center;">
<div style="width: 50%; margin: 0px auto; text-align:left;">Text</div>
</div>
The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.
Use:
#outerDiv {
width: 500px;
}
#innerDiv {
width: 200px;
margin: 0 auto;
}
<div id="outerDiv">
<div id="innerDiv">Inner Content</div>
</div>
Another solution for this without having to set a width for one of the elements is using the CSS 3 transform attribute.
#outer {
position: relative;
}
#inner {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
The trick is that translateX(-50%) sets the #inner element 50 percent to the left of its own width. You can use the same trick for vertical alignment.
Here's a Fiddle showing horizontal and vertical alignment.
More information is on Mozilla Developer Network.
Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support than the Flexbox solution, and you're not using display: table; which could break other things.
/* This parent can be any width and height */
.outer {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.outer:before {
content: '.';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
overflow: hidden;
}
/* The element to be centered, can
also be of any width and height */
.inner {
display: inline-block;
vertical-align: middle;
width: 300px;
}
I recently found an approach:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
Both elements must be the same width to function correctly.
For example, see this link and the snippet below:
div#outer {
height: 120px;
background-color: red;
}
div#inner {
width: 50%;
height: 100%;
background-color: green;
margin: 0 auto;
text-align: center; /* For text alignment to center horizontally. */
line-height: 120px; /* For text alignment to center vertically. */
}
<div id="outer" style="width:100%;">
<div id="inner">Foo foo</div>
</div>
If you have a lot of children under a parent, so your CSS content must be like this example on fiddle.
The HTML content look likes this:
<div id="outer" style="width:100%;">
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> Foo Text </div>
</div>
Then see this example on fiddle.
Centering only horizontally
In my experience, the best way to center a box horizontally is to apply the following properties:
The container:
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.container {
width: 100%;
height: 120px;
background: #CCC;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="container">
<div class="centered-content">
Center this!
</div>
</div>
See also this Fiddle!
Centering both horizontally & vertically
In my experience, the best way to center a box both vertically and horizontally is to use an additional container and apply the following properties:
The outer container:
should have display: table;
The inner container:
should have display: table-cell;
should have vertical-align: middle;
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.outer-container {
display: table;
width: 100%;
height: 120px;
background: #CCC;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Center this!
</div>
</div>
</div>
See also this Fiddle!
Flexbox
display: flex behaves like a block element and lays out its content according to the flexbox model. It works with justify-content: center.
Please note: Flexbox is compatible all browsers exept Internet Explorer. See display: flex not working on Internet Explorer for a complete and up to date list of browsers compatibility.
#inner {
display: inline-block;
}
#outer {
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Text-align: center
Applying text-align: center the inline contents are centered within the line box. However since the inner div has by default width: 100% you have to set a specific width or use one of the following:
display: block
display: inline
display: inline-block
#inner {
display: inline-block;
}
#outer {
text-align: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Margin: 0 auto
Using margin: 0 auto is another option and it is more suitable for older browsers compatibility. It works together with display: table.
#inner {
display: table;
margin: 0 auto;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Transform
transform: translate lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require position: absolute and left: 50%.
#inner {
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
<center> (Deprecated)
The tag <center> is the HTML alternative to text-align: center. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.
#inner {
display: inline-block;
}
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
This method also works just fine:
div.container {
display: flex;
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
For the inner <div>, the only condition is that its height and width must not be larger than the ones of its container.
The easiest way:
#outer {
width: 100%;
text-align: center;
}
#inner {
margin: auto;
width: 200px;
}
<div id="outer">
<div id="inner">Blabla</div>
</div>
Flex have more than 97% browser support coverage and might be the best way to solve these kind of problems within few lines:
#outer {
display: flex;
justify-content: center;
}
If width of the content is unknown you can use the following method. Suppose we have these two elements:
.outer -- full width
.inner -- no width set (but a max-width could be specified)
Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:
Wrap .inner inside .center-helper
Make .center-helper an inline block; it becomes the same size as .inner making it 300 pixels wide.
Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.
Set overflow on .outer to hidden to prevent horizontal scrollbar.
Demo:
body {
font: medium sans-serif;
}
.outer {
overflow: hidden;
background-color: papayawhip;
}
.center-helper {
display: inline-block;
position: relative;
left: 50%;
background-color: burlywood;
}
.inner {
display: inline-block;
position: relative;
left: -50%;
background-color: wheat;
}
<div class="outer">
<div class="center-helper">
<div class="inner">
<h1>A div with no defined width</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>
Duis condimentum sem non turpis consectetur blandit.<br>
Donec dictum risus id orci ornare tempor.<br>
Proin pharetra augue a lorem elementum molestie.<br>
Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>
</div>
</div>
</div>
You can do something like this
#container {
display: table;
width: <width of your container>;
height: <height of your container>;
}
#inner {
width: <width of your center div>;
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
}
This will also align the #inner vertically. If you don't want to, remove the display and vertical-align properties;
Here is what you want in the shortest way.
JSFIDDLE
#outer {
margin - top: 100 px;
height: 500 px; /* you can set whatever you want */
border: 1 px solid# ccc;
}
#inner {
border: 1 px solid# f00;
position: relative;
top: 50 % ;
transform: translateY(-50 % );
}
You can use display: flex for your outer div and to horizontally center you have to add justify-content: center
#outer{
display: flex;
justify-content: center;
}
or you can visit w3schools - CSS flex Property for more ideas.
Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:
Here's the structure:
<div class="container">
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
</div>
And here's the JavaScript snippet:
$(document).ready(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
If you want to use it in a responsive approach, you can add the following:
$(window).resize(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
One option existed that I found:
Everybody says to use:
margin: auto 0;
But there is another option. Set this property for the parent div. It
works perfectly anytime:
text-align: center;
And see, child go center.
And finally CSS for you:
#outer{
text-align: center;
display: block; /* Or inline-block - base on your need */
}
#inner
{
position: relative;
margin: 0 auto; /* It is good to be */
}
How can I horizontally center a <div> within another <div> using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
With flexbox it is very easy to style the div horizontally and vertically centered.
#inner {
border: 0.05em solid black;
}
#outer {
border: 0.05em solid red;
width:100%;
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
To align the div vertically centered, use the property align-items: center.
Other Solutions
You can apply this CSS to the inner <div>:
#inner {
width: 50%;
margin: 0 auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width.
Working example here:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
If you don't want to set a fixed width on the inner div you could do something like this:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
That makes the inner div into an inline element that can be centered with text-align.
The best approaches are with CSS3.
The old box model (deprecated)
display: box and its properties box-pack, box-align, box-orient, box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.
#outer {
width: 100%;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
#inner {
width: 50%;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
According to your usability you may also use the box-orient, box-flex, box-direction properties.
The modern box model with Flexbox
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
Read more about centering the child elements
CSS Box Model Module Level 3
Box model (CSS2)
box-align on MDN
And this explains why the box model is the best approach:
Why is the W3C box model considered better?
#centered {
position: absolute;
left: 50%;
margin-left: -100px;
}
<div id="outer" style="width:200px">
<div id="centered">Foo foo</div>
</div>
Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.
If you don't know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.
With CSS calc(), the code can get even simpler:
.centered {
width: 200px;
position: absolute;
left: calc(50% - 100px);
}
The principle is still the same; put the item in the middle and compensate for the width.
I've created this example to show how to vertically and horizontally align.
The code is basically this:
#outer {
position: relative;
}
and...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
And it will stay in the center even when you resize your screen.
Some posters have mentioned the CSS 3 way to center using display:box.
This syntax is outdated and shouldn't be used anymore. [See also this post].
So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module.
So if you have simple markup like:
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...and you want to center your items within the box, here's what you need on the parent element (.box):
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box {
display: flex;
flex-wrap: wrap;
/* Optional. only if you want the items to wrap */
justify-content: center;
/* For horizontal alignment */
align-items: center;
/* For vertical alignment */
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
.box {
height: 200px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border: 2px solid tomato;
}
.box div {
margin: 0 10px;
width: 100px;
}
.item1 {
height: 50px;
background: pink;
}
.item2 {
background: brown;
height: 100px;
}
.item3 {
height: 150px;
background: orange;
}
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
If you need to support older browsers which use older syntax for flexbox here's a good place to look.
If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.
You can use:
#element {
display: table;
margin: 0 auto;
}
Centering a div of unknown height and width
Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)
.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>
Tinker with it further on Codepen or on JSBin.
Set the width and set margin-left and margin-right to auto. That's for horizontal only, though. If you want both ways, you'd just do it both ways. Don't be afraid to experiment; it's not like you'll break anything.
It cannot be centered if you don't give it a width. Otherwise, it will take, by default, the whole horizontal space.
CSS 3's box-align property
#outer {
width: 100%;
height: 100%;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
The way I usually do it is using absolute position:
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
The outer div doesn't need any extra properties for this to work.
I recently had to center a "hidden" div (i.e., display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn't necessary to display.)
NOTE: I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and can't be resized/centered until after they are displayed.
$(function(){
$('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inner" style="display:none;">
<form action="">
<table id="innerTable">
<tr><td>Name:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="submit"></td></tr>
</table>
</form>
</div>
For Firefox and Chrome:
<div style="width:100%;">
<div style="width: 50%; margin: 0px auto;">Text</div>
</div>
For Internet Explorer, Firefox, and Chrome:
<div style="width:100%; text-align:center;">
<div style="width: 50%; margin: 0px auto; text-align:left;">Text</div>
</div>
The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.
Use:
#outerDiv {
width: 500px;
}
#innerDiv {
width: 200px;
margin: 0 auto;
}
<div id="outerDiv">
<div id="innerDiv">Inner Content</div>
</div>
Another solution for this without having to set a width for one of the elements is using the CSS 3 transform attribute.
#outer {
position: relative;
}
#inner {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
The trick is that translateX(-50%) sets the #inner element 50 percent to the left of its own width. You can use the same trick for vertical alignment.
Here's a Fiddle showing horizontal and vertical alignment.
More information is on Mozilla Developer Network.
Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support than the Flexbox solution, and you're not using display: table; which could break other things.
/* This parent can be any width and height */
.outer {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.outer:before {
content: '.';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
overflow: hidden;
}
/* The element to be centered, can
also be of any width and height */
.inner {
display: inline-block;
vertical-align: middle;
width: 300px;
}
I recently found an approach:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
Both elements must be the same width to function correctly.
For example, see this link and the snippet below:
div#outer {
height: 120px;
background-color: red;
}
div#inner {
width: 50%;
height: 100%;
background-color: green;
margin: 0 auto;
text-align: center; /* For text alignment to center horizontally. */
line-height: 120px; /* For text alignment to center vertically. */
}
<div id="outer" style="width:100%;">
<div id="inner">Foo foo</div>
</div>
If you have a lot of children under a parent, so your CSS content must be like this example on fiddle.
The HTML content look likes this:
<div id="outer" style="width:100%;">
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> Foo Text </div>
</div>
Then see this example on fiddle.
Centering only horizontally
In my experience, the best way to center a box horizontally is to apply the following properties:
The container:
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.container {
width: 100%;
height: 120px;
background: #CCC;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="container">
<div class="centered-content">
Center this!
</div>
</div>
See also this Fiddle!
Centering both horizontally & vertically
In my experience, the best way to center a box both vertically and horizontally is to use an additional container and apply the following properties:
The outer container:
should have display: table;
The inner container:
should have display: table-cell;
should have vertical-align: middle;
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.outer-container {
display: table;
width: 100%;
height: 120px;
background: #CCC;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Center this!
</div>
</div>
</div>
See also this Fiddle!
Flexbox
display: flex behaves like a block element and lays out its content according to the flexbox model. It works with justify-content: center.
Please note: Flexbox is compatible all browsers exept Internet Explorer. See display: flex not working on Internet Explorer for a complete and up to date list of browsers compatibility.
#inner {
display: inline-block;
}
#outer {
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Text-align: center
Applying text-align: center the inline contents are centered within the line box. However since the inner div has by default width: 100% you have to set a specific width or use one of the following:
display: block
display: inline
display: inline-block
#inner {
display: inline-block;
}
#outer {
text-align: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Margin: 0 auto
Using margin: 0 auto is another option and it is more suitable for older browsers compatibility. It works together with display: table.
#inner {
display: table;
margin: 0 auto;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Transform
transform: translate lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require position: absolute and left: 50%.
#inner {
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
<center> (Deprecated)
The tag <center> is the HTML alternative to text-align: center. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.
#inner {
display: inline-block;
}
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
This method also works just fine:
div.container {
display: flex;
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
For the inner <div>, the only condition is that its height and width must not be larger than the ones of its container.
The easiest way:
#outer {
width: 100%;
text-align: center;
}
#inner {
margin: auto;
width: 200px;
}
<div id="outer">
<div id="inner">Blabla</div>
</div>
Flex have more than 97% browser support coverage and might be the best way to solve these kind of problems within few lines:
#outer {
display: flex;
justify-content: center;
}
If width of the content is unknown you can use the following method. Suppose we have these two elements:
.outer -- full width
.inner -- no width set (but a max-width could be specified)
Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:
Wrap .inner inside .center-helper
Make .center-helper an inline block; it becomes the same size as .inner making it 300 pixels wide.
Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.
Set overflow on .outer to hidden to prevent horizontal scrollbar.
Demo:
body {
font: medium sans-serif;
}
.outer {
overflow: hidden;
background-color: papayawhip;
}
.center-helper {
display: inline-block;
position: relative;
left: 50%;
background-color: burlywood;
}
.inner {
display: inline-block;
position: relative;
left: -50%;
background-color: wheat;
}
<div class="outer">
<div class="center-helper">
<div class="inner">
<h1>A div with no defined width</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>
Duis condimentum sem non turpis consectetur blandit.<br>
Donec dictum risus id orci ornare tempor.<br>
Proin pharetra augue a lorem elementum molestie.<br>
Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>
</div>
</div>
</div>
You can do something like this
#container {
display: table;
width: <width of your container>;
height: <height of your container>;
}
#inner {
width: <width of your center div>;
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
}
This will also align the #inner vertically. If you don't want to, remove the display and vertical-align properties;
Here is what you want in the shortest way.
JSFIDDLE
#outer {
margin - top: 100 px;
height: 500 px; /* you can set whatever you want */
border: 1 px solid# ccc;
}
#inner {
border: 1 px solid# f00;
position: relative;
top: 50 % ;
transform: translateY(-50 % );
}
You can use display: flex for your outer div and to horizontally center you have to add justify-content: center
#outer{
display: flex;
justify-content: center;
}
or you can visit w3schools - CSS flex Property for more ideas.
Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:
Here's the structure:
<div class="container">
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
</div>
And here's the JavaScript snippet:
$(document).ready(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
If you want to use it in a responsive approach, you can add the following:
$(window).resize(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
One option existed that I found:
Everybody says to use:
margin: auto 0;
But there is another option. Set this property for the parent div. It
works perfectly anytime:
text-align: center;
And see, child go center.
And finally CSS for you:
#outer{
text-align: center;
display: block; /* Or inline-block - base on your need */
}
#inner
{
position: relative;
margin: 0 auto; /* It is good to be */
}
I want to have an avatar image with two divs on its right that are vertically aligned to it.
https://jsbin.com/qafiroquve/1/edit?html,css,output
I've read so many posts about this, but none of them seems to help me.
What is the best approach to having the image on the left with 30% of the main div's (header) width, and the info div with 70% of it?
If either of the info divs (name or position) has too much text, I want the info div to get vertically aligned to the image on its left.
I also want this info div to have a margin with the image.
I've tried so many options: float: left on avatar div, display: inline-block on both avatar and info, width: 30% and 40% . I don't want to use bootstrap for this purpose as it complicates things and I want to keep it as simple as possible.
You can use either table-cell how #w3debugger suggested or you can take advantage of a quick css hack to align vertically:
.yourclass{
position:absolute;
top: 50%;
transform: translateY(-50%)
}
But that needs the parent of .yourclass to be position:relative and be of type display:block; If your parent is block it will take the height of the block that is inside it, so the avatar, that is next to .yourclass needs to be display:block as well,
I edited your example:
HTML:
<div class="header">
<div class="avatar">
<img src="http://i.imgur.com/pBcut2e.jpg" />
</div><div class="info">
<div class="name">Important person here </div>
<div class="position">CHIEF DIGITAL STRATEGIST & CO-FOUNDER</div>
</div>
</div>
CSS:
.header {
width: 500px;
background: aqua;
margin: 0 auto;
padding: 10px;
position: relative;
}
.avatar img {
width: 30%;
border-radius: 50%;
}
.info{
box-sizing: border-box;
padding: 0 40px;
width: 70%;
position:absolute;
right: 0;
vertical-align: top;
top: 50%;
transform: translateY(-50%)
}
Live preview:
https://jsbin.com/gogewefizo/1/edit?html,css,output
Unfortunately, vertical-align didn't work with float elements. You should use display: table-cell or `display: inline-block in order to meet your requirements.
Please check the code below.
.header {
width: 500px;
background: aqua;
margin: 0 auto;
padding: 10px;
display: table;
}
.avatar img {
width: 150px;
}
.avatar,
.info {
display: table-cell;
vertical-align: middle;
}
<div class="header">
<div class="avatar">
<img src="http://i.imgur.com/pBcut2e.jpg" />
</div>
<div class="info">
<div class="name">Important person here</div>
<div class="position">CHIEF DIGITAL STRATEGIST & CO-FOUNDER</div>
</div>
</div>
Please visit this fiddle to see what I mean -
I have a parent DIV, within that there are two DIVs placed in vertical order.
The top DIV should have only the height of its content, whereas the bottom DIV should occupy all remain space of the parent DIV irrespective to content heights, and also shouldn't overlap the parent DIV.
HTML:
<div class="outer">
<div class="inner-title">
THIS IS MY TITLE
</div>
<div class="inner-content">
CONTENT AREA
</div>
</div>
CSS:
html,body
{
height: 100%;
}
.outer
{
background-color:blue;
height: 80%;
}
.inner-title
{
background-color:red;
}
.inner-content
{
background-color:yellow;
height: auto;
}
In short, "inner-content" should occupy all remaining space of "outer" DIV, without overlapping.
Any idea of how to achieve this?
Any help on this much appreciated.
Add display:table; to parent div and display:table-row; to child divs
And height:0 to first child div. This takes auto height
html,body{
height: 100%;
}
.outer{
background-color:blue;
height: 80%; border:red solid 2px;
display: table;
width:100%
}
.inner-title{
background-color:red;
display:table-row;
width:100%
}
.inner-content{
background-color:grey;
display:table-row;
width:100%;
height:100%
}
DEMO UPDATED
A newer CSS way would be using flexbox
/*QuickReset*/ *{box-sizing:border-box;margin:0;} html,body{height:100%;}
.flex-col {
display: flex;
flex-direction: column; /* or: flex-flow: column wrap; */
height: 100%;
}
.flex-fill { /* Add this class to the element you want to expand */
flex: 1;
}
<div class="flex-col">
<div style="background:red;"> HEADER </div>
<div class="flex-fill" style="background:yellow;"> CONTENT </div>
<div style="background:red;"> FOOTER</div>
</div>
I have a markup like this:
<div>
<img />
</div>
The div is higher than img:
div {
height: 100px;
}
img {
height: dynamic-value-smaller-than-100px;
}
I need the image to be in the middle of the div (have same amout of white space above and below it).
I tried this and it does not work:
div {
vertical-align: middle;
}
if your image is purely decorative, then it might be a more semantic solution to use it as a background-image. You can then specify the position of the background
background-position: center center;
If it is not decorative and constitutes valuable information then the img tag is justified. What you need to do in such case is style the containing div with the following properties:
div{
display: table-cell; vertical-align: middle
}
Read more about this technique here. Reported to not work on IE6/7 (works on IE8).
Another way is to set your line-height in the container div, and align your image to that using vertical-align: middle.
html:
<div class="container"><img></div>
css:
.container {
width: 200px; /* or whatever you want */
height: 200px; /* or whatever you want */
line-height: 200px; /* or whatever you want, should match height */
text-align: center;
}
.container > img {
vertical-align: middle;
}
It's off the top of my head. But I've used this before - it should do the trick. Works for older browsers as well.
Let's say you want to put the image (40px X 40px) on the center (horizontal and vertical) of the div class="box". So you have the following html:
<div class="box"><img /></div>
What you have to do is apply the CSS:
.box img {
position: absolute;
top: 50%;
margin-top: -20px;
left: 50%;
margin-left: -20px;
}
Your div can even change it's size, the image will always be on the center of it.
This is a solution I've used before to accomplish vertical centering in CSS. This works in all the modern browsers.
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
Excerpt:
<div style="display: table; height: 400px; position: relative; overflow: hidden;">
<div style="position: absolute; top: 50%;display: table-cell; vertical-align: middle;">
<div style="position: relative; top: -50%">
any text<br>
any height<br>
any content, for example generated from DB<br>
everything is vertically centered
</div>
</div>
</div>
(Inline styles for demonstration purposes)
Another option is to set display:block on the img and then set margin: 0px auto;
img{
display: block;
margin: 0px auto;
}
As I too am constantly being let down by cross-browser CSS, I'd like to offer a JQuery solution here. This takes the height of each image's parent div, divide it by two and set it as a top margin between the image and the div:
$('div img').each(function() {
m = Math.floor(($(this).parent('div').height() - $(this).height())/2);
mp = m+"px";
$(this).css("margin-top",mp);
});
There are five possible ways for centering an image with any size with pure CSS.
Using flex and making the img tag be inside (best solution for modern browsers):
div {
display: flex;
align-items: center;
justify-content: center
}
Putting the image in background-image and using background-position (as #pixeline explained):
div {
background-image: url(...);
background-position:center center
}
Using display: table for parent element, and using display: table-cell with vertical-align: middle for child element:
div.parent {
display: table;
}
div.child {
display: table-cell;
vertical-align: middle;
}
Using position:absolute with transform for the image and parent element position be not unset:
div {
position: relative;
}
div > img {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
Using line-height as same height of the element, then using vertical-align (in my opinion, the best solution for supporting more browsers like IE9>).
Note: In some old browsers, sometimes for using this way safely, you need to have at least one character in the line that the image exist. For fixing this issue, I used a non-breakable space in a pseudo-element of the parent.
As in the following example:
div {
display: block;
height: 200px;
width: 200px;
background-color: purple;
line-height: 200px;
text-align: center;
}
div:after {
content: "\a0";
}
div > img {
vertical-align: middle;
}
<div><img src="https://via.placeholder.com/100.png/09f/fff" /></div>
I've posted about vertical alignment it in cross-browser way (Vertically center multiple boxes with CSS)
Create one-cell table. Only table has cross-browser vertical-align
image to be in the middle of the div
div img{
bottom: 0;
left: 0;
margin: auto;
position: absolute;
right: 0;
top: 0;
height:50px;
width:50px;
}
In your example, the div's height is static and the image's height is static. Give the image a margin-top value of ( div_height - image_height ) / 2
If the image is 50px, then
img {
margin-top: 25px;
}
Have you tried setting margin on the div? e.g.
div {
padding: 25px, 0
}
for top and bottom. You may also be able to use a percentage:
div {
padding: 25%, 0
}
<div style="background-color:#006600; width:300px; text-align:center; padding:50px 0px 50px 0px;">
<img src="imges/import.jpg" width="200" height="200"/>
</div>
The accepted answer did not work for me. vertical-align needs a partner so that they can be aligned at their centers. So I created an empty div with full height of the parent div but with no width for the image to align with. inline-block is needed for both objects to stay in one line.
<div>
<div class="placeholder"></div>
<img />
</div>
CSS:
.class {
height: 100%;
width: 0%;
vertical-align: middle;
display: inline-block
}
img {
display: inline-block;
vertical-align: middle;
}
div {
width:200px;
height:150px;
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
display:box;
box-pack:center;
box-align:center;
}
<div>
<img src="images/logo.png" />
</div>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
(function ($) {
$.fn.verticalAlign = function() {
return this.each(function(i){
var ah = $(this).height();
var ph = $(this).parent().height();
var mh = Math.ceil((ph-ah)/2);
$(this).css('margin-top', mh);
});
};
})(jQuery);
$(document).ready(function(e) {
$('.in').verticalAlign();
});
</script>
<style type="text/css">
body { margin:0; padding:0;}
.divWrap { width:100%;}
.out { width:500px; height:500px; background:#000; text-align:center; padding:1px; }
.in { width:100px; height:100px; background:#CCC; margin:0 auto; }
</style>
</head>
<body>
<div class="divWrap">
<div class="out">
<div class="in">
</div>
</div>
</div>
</body>
</html>
If you want content to be what ever you need to have inside a div, this did the job for me:
<div style="
display: table-cell;
vertical-align: middle;
background-color: blue;
width: ...px;
height: ...px;
">
<div style="
margin: auto;
display: block;
width: fit-content;
">
<!-- CONTENT -->
<img src="...">
<p> some text </p>
</div>
</div>