html - 断行时 CSS 居中 DIV

标签 html css css-float centering

我试图在断行时设置 .container 的内容。我不知道如何同时使用 float:left 和 center。我认为两者都是独家的。

div.container {
  border: solid 1px black;
  text-align: center;
}

div.floatfix:after {
  content: '';
  display: block;
  clear: both;
}

div.item {
  float: left;
  border: solid 1px red;
  padding: 5px;
}
<div class="container floatfix">
  <div class="item">First Item</div>
  <div class="item">Another Item</div>
  <div class="item">Just Another Item</div>
  <div class="item">Middle Item</div>
  <div class="item">Item</div>
  <div class="item">Last Item</div>
  <div class="item">Realy Last Item</div>
</div>

我想得到如下效果 enter image description here

最佳答案

您应该在元素上使用 display: inline-block; 而不是 float: left;

然后您可以使用以下内容修改容器的样式:

  • margin: auto: 在页面居中
  • text-align: auto:将内容居中
  • width: ...px: 限制宽度

这给你:

div.container {
  border: solid 1px black;
  text-align: center;
  width: 200px;
  margin: auto;
  text-align: center;
}

div.floatfix:after {
  content: '';
  display: block;
  clear: both;
}

div.item {
  display: inline-block;
  border: solid 1px red;
  padding: 5px;
}
<div class="container floatfix">
  <div class="item">First Item</div>
  <div class="item">Another Item</div>
  <div class="item">Just Another Item</div>
  <div class="item">Middle Item</div>
  <div class="item">Item</div>
  <div class="item">Last Item</div>
  <div class="item">Realy Last Item</div>
</div>

关于html - 断行时 CSS 居中 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32246094/

相关文章:

html - CouchCMS - float 元素未正确 float

jQuery - .each() 输入值进行比较

html - 是什么导致我的 Bootstrap col 在中间断点处有大顶部 'margin'?

css - 把之前的div放到 "float atribute"下面去

javascript - 第一个元素编号显示在最右侧,但所有其他元素编号都向左浮动,我如何将 1 放在它应该出现的位置?

javascript - 查询 : Sliding Puzzle Generator Giving Unsolvable Puzzles

php - 如何防止自动递增跳过 mysql 数据库中的 ID 号?

javascript - 使用 Linkedin 代码登录给我 html 验证错误

html - 为什么没有使用移动 CSS

html - 为什么媒体查询在此示例中不更改字体大小?