如何在不同位置拥有不同的div?

3

我将对我的div位置进行以下设置:

  1. 如果我有两个div,则它们应该位于页面中间
  2. 如果我有三个div,则它们应该位于一行
  3. 如果我有四个div,则其中三个应该在一行上,最后一个应该在下一行的左边
  4. 如果我有五个div,则其中三个应该在一行上,另外两个应该在下一行的中间

我的问题是当我有四个div时,最后一个div位于下一行的中间。

这是我的代码:

HTML

<div id="cards-overview" class="mt60"> 
    <div class="row-fluid" >
        <div class="span12">
            <div th:each="card, cardStat : ${dashboard.cards}"
                class="card-container-outer" style="display:      inline-block; text-align:left">
                <div class="card-container pointer">
                    <div th:switch="${card.status}">
                        <i th:id="${'card-status-' + card.windPowerStationId}"
                            th:case="1"
                            class="icon-status icon-status-ok card-status-tooltip navy-tooltip">
                            <span
                            th:id="${'card-status-description-' + card.windPowerStationId}"
                            th:text="${card.statusDescription}"></span>
                        </i> 
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.mt60 {
margin-top: 60px;
text-align: center;
}

.card-container-outer {
width: 480px;
}

.card-container {
margin-left: auto;
margin-right: auto;
width: 310px;
height: 510px;
position: relative;
}

1
你需要使用百分比而不是固定像素,例如网格系统。这样你的问题就会自然解决了。 - Mutu Yolbulan
不幸的是,它也不能使用百分比。我将宽度设置为26%,当我有4个div时得到相同的结果。 - Gilana
你试过这个吗?http://masonry.desandro.com/demos/animating-css-transitions.html - abbood
2个回答

0

(提示:margin: 0 auto;比margin-left和margin-right auto更好)

您可以通过在容器上放置以下内容来使第一行居中并将最后一行左对齐:

text-align: center;
text-align-last: left;

0
你可以使用 display:inline-block 使这些容器更加可塑,同时将整个容器设置为 text-align:center - 这样它们就会相互叠加。然后,如果你编写一小段 jQuery 代码来检查有多少个“容器”,并为最后一个元素分配其对齐属性。
var number = $('#containers').length();
if(number===4){
  $('#containers').last().css(//change the css properties to make the last div float left)
}

您可以放置许多不同的if/else参数来确定对齐方式应该是什么。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接