How to center elements inside a div?

This question already has an answer here:

I have some divs inside a main div, but I have looked every questions similar to this and I have tried many things but I couldn’t center them horizontally. I could only make them on the other side but not the center.

.ground {
  width: 390px;
  height: 575px;
  border: 1px solid white;
}

.line {
  padding: 10px
}

.active {
  width: 30px;
  height: 30px;
  opacity: 0.5;
  background: gray;
  -moz-border-radius: 60px;
  -webkit-border-radius: 60px;
  border-radius: 100px;
  display: inline-block;
  border: 2px solid black;
}

.nonactive {
  width: 30px;
  height: 30px;
  opacity: 1.0;
  background: lime;
  -moz-border-radius: 60px;
  -webkit-border-radius: 60px;
  border-radius: 100px;
  display: inline-block;
  border: 2px solid black;
}

Here is the jsfiddle demo

You can see those 5 circles are the ones I need to center them inside the main div ground.


solution

In your case, the simplest way to do this would be to set the display of the .line element to inline-block so that it has a “shrink-to-fit” width. In doing so, it will have the same width as its children elements. Then add text-align: center to the parent element to center the inline child element:

Updated Example

.ground { text-align: center; }
.ground .line { display: inline-block; }

See this answer for a few alternatives.