“中心左侧”与css

时间:2016-03-03 00:34:26

标签: css alignment

很难解释我想要的东西,所以我将展示我想要的结果的动画gif(在photoshop中制作)和我在jsFiddle中的代码。

magic

如您所见,当蓝框大小不足以容纳一行中的所有项目时,4º项目将移动到第二行(如预期的那样),但不是在中心对齐,而是左对齐

我的CSS代码

.outer-box
{
  background: #00cc99;
  width: 100%;
  max-width: 800px;
  font-size: 0;
  text-align: center;
  padding: 10px;
}

.outer-box a
{
  display: inline-block;
  width: 120px;
  height: 80px;
  padding: 10px;
  background: #ff5050;
  font-size: 12px;
}

.outer-box a:hover
{
  background: #990000;
}

.outer-box a div
{
  background: #99ccff;
  width: 100%;
  height: 100%;
}

我的HTML

<div class="outer-box">
  <a href="#"><div>I put image and text here</div></a>
  <a href="#"><div>I put image and text here</div></a>
  <a href="#"><div>I put image and text here</div></a>
  <a href="#"><div>I put image and text here</div></a>
</div>

我的结果
My Result (fail)

我的预期结果
My Expected Result

我尝试使用float divs(外部框中的一个div和使用float左侧的链接元素)但没有成功。

有一种方法可以在没有javascript的情况下实现这一点吗? 这是jsFiddle中的代码。

PS。英语不是我的母语' - '。

3 个答案:

答案 0 :(得分:2)

使用flex或inline块,你可以使用1px高度的伪和2个盒子的宽度+它们的边距。

它将像一个fith框,完全填充第二行并作为第三行删除:

.outer-box {
  background: #00cc99;
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin: auto;
  font-size: 0;
  padding: 10px;
}

.outer-box:after {
  content: '';
  max-height: 1px;
  width: 320px
}

.outer-box a {
  display: block;
  width: 120px;
  height: 80px;
  padding: 10px;
  background: #ff5050;
  font-size: 12px;
  margin: 5px 10px;
}

.outer-box a:hover {
  background: #990000;
}

.outer-box a div {
  background: #99ccff;
  height: 100%;
}
<h1> USE full page mode then resize window broser </h1>
<div class="outer-box">
  <a href="#"><div>I put image and text here</div></a>
  <a href="#"><div>I put image and text here</div></a>
  <a href="#"><div>I put image and text here</div></a>
  <a href="#"><div>I put image and text here</div></a>
</div>

Inline-block version to play with

答案 1 :(得分:1)

首先,我喜欢你提出问题的方式。漂亮的图片: - )

如果没有额外的元素,我认为你不能做你想做的事。添加一个重新调整对齐的内联块元素可以达到你想要的效果。

.inner-box {
  text-align: left;
  display: inline-block;
}

请参阅https://jsfiddle.net/qgcz0ax4/

答案 2 :(得分:0)

由于<a>标记,每个div都充当文本。只需将text-align设置为左侧的.outer-box - 如果你希望每个div都有中心对齐的文本,创建一个类并将该类赋予所有4个子div

.outer-box
{
  background: #00cc99;
  width: 100%;
  max-width: 800px;
  font-size: 0;
  text-align: left;
  padding: 10px;
}
相关问题