简体   繁体   English

如何将左浮动元素居中?

[英]How do I center left-floated elements?

I have a container of various width, and various number of boxes float inside it. 我有一个各种宽度的容器,里面有不同数量的盒子。 All the boxes have same width and height . 所有盒子都有相同的widthheight

This is a demonstration. 这是一个示范。 https://jsfiddle.net/kghvmjb6/1/ https://jsfiddle.net/kghvmjb6/1/

I am looking for pure CSS solution if possible. 如果可能的话,我正在寻找纯CSS解决方案。 Otherwise pure javascript (no jQuery) and CSS solutions are fine. 否则纯javascript(没有jQuery)和CSS解决方案都可以。

This example works fine with one line of floating boxes but fail with multiple lines, which is not I want. 这个例子适用于一行浮动框但是多行失败,这不是我想要的。 https://codepen.io/alexandredees/pen/ojaFr https://codepen.io/alexandredees/pen/ojaFr

Instead of using float left , use display inline-block and in the parent div add text-align center , that will center the boxes in the container 而不是使用float left ,使用display inline-block并在父div添加text-align center ,这将使container的框居中

Modified Fiddle 改良小提琴

HTML HTML

<div class="container">
 <div class="">
   <div class="box">1</div>
   <div class="box">2</div>
   <div class="box">3</div>
   <div class="box">4</div>
   <div class="box">5</div>
   <div class="box">6</div>
   <div class="clear"></div>
 </div>
</div>

CSS CSS

.container {
   border: 1px solid red;
   width: 480px; text-align:center;
 }

  .container.wider {
    width: 530px;
  }

 .box {
   float: none;
   width: 80px;
   height: 80px;
   margin: 10px;
   background-color: #ddd;
   display:inline-block;
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM