232

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.

The Codesee
  • 3,714
  • 5
  • 38
  • 78
Randomblue
  • 112,777
  • 145
  • 353
  • 547

23 Answers23

341

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/

Neuron
  • 5,141
  • 5
  • 38
  • 59
pasine
  • 11,311
  • 10
  • 49
  • 81
84

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>
Community
  • 1
  • 1
Gerard Reches
  • 3,048
  • 3
  • 28
  • 39
12

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/

Warface
  • 5,029
  • 9
  • 56
  • 82
9

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.

סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
Romi Erez
  • 477
  • 4
  • 5
7

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>
Ayan
  • 8,192
  • 4
  • 46
  • 51
6

text-align:center; on the parent div Should do the trick

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
2

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

kmartinho
  • 144
  • 1
  • 10
  • 1
    Note: Also requires: `display:grid;` - both instructions *(display/place-items)* applied to the parent container. Also note that the parent container needs a height in order to center vertically. *(Works very similar to the flexbox solution (also applied to the parent container):* ***`display:flex; justify-content:center; align-items:center;`*** *)* – cssyphus Aug 29 '20 at 17:15
2

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;
}
Purag
  • 16,941
  • 4
  • 54
  • 75
2

just give the parent div position: relative

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189
1

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.

1

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>
Parthis
  • 359
  • 1
  • 10
0

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;
}
Squeeky91
  • 11
  • 2
0

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

Ruben
  • 290
  • 3
  • 14
0

Assign text-align: center; to the parent and display: inline-block; to the div.

koulikoff
  • 11
  • 4
0

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

Hylke
  • 11
0

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.

QMaster
  • 3,743
  • 3
  • 43
  • 56
0

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>
Azizi Musa
  • 1,009
  • 2
  • 10
  • 31
0
<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>
Suraj Patil
  • 180
  • 2
  • 4
0

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; } 
Ehtesham
  • 2,967
  • 1
  • 18
  • 20
0

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.

Bardt
  • 695
  • 1
  • 8
  • 17
0

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.

Spyros
  • 126
  • 2
  • 9
0

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>
0

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>
mike_s
  • 111
  • 4