如何将div中的元素居中?

时间:2015-12-11 18:13:32

标签: css

我在一个主div中有一些div,但是我已经看过每个与此类似的问题,我尝试过很多东西,但是我无法横向居中。我只能把它们放在另一边而不是中心。

.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;
}

以下是jsfiddle demo

你可以看到这5个圆圈是我需要将它们放在主div地面内的圆圈。

2 个答案:

答案 0 :(得分:6)

在您的情况下,最简单的方法是将<div class="ground"> <div class="line"> <div id="def" class="active"></div> <div id="def" class="active"></div> <div id="def" class="active"></div> <div id="def" class="active"></div> <div id="def" class="active"></div> </div> </div>元素的display设置为.line,使其具有"shrink-to-fit" width。这样做,它将具有与其子元素相同的宽度。然后将inline-block添加到父元素以使内联子元素居中:

Updated Example

text-align: center

有关其他选择,请参阅this answer

答案 1 :(得分:1)

您可以使用flexbox居中。 display: flex在父元素上会将圆圈居中。

JSfiddle Demo

&#13;
&#13;
justify-content: center
&#13;
.ground {
  width: 390px;
  height: 575px;
  background-image: url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAxgDGAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAKAAoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD49bqCD1/CgT7RjA4+lEZ4b2A/lTa/Dj86Z//Z);
  border: 1px solid white;
  display: flex;
  justify-content: center;
}
.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;
}
&#13;
&#13;
&#13;