我完全是编程新手。我已经对齐了5个盒装水平,但我想要的是将盒子居中。这些盒子也应该响应它们现在的状态。我正在搜索和搜索如何居中div,但结果我得到了
.square {
float:left;
width: 12.5vw;
height: 12.5vw;
margin-left: 10px;
margin-right: 10px;
position: relative;
border: 0.5px solid red;
text-align: center;
}
.square span {
font-size: 3vw;
}
。当我将浏览器调整为100%时,第5个框会进入其他框。
<div class="outside">
<div class="square">
<span>2.1</span>
</div>
<div class="square">
<span>2.3</span>
</div>
<div class="square">
<span>2.5</span>
</div>
<div class="square">
<span>2.6</span>
</div>
<div class="square">
<span>2.7</span>
</div>
</div>
JSON
答案 0 :(得分:0)
将max-width
或width
添加到父容器。然后用margin: 0 auto
居中。当然,根据需要设置父元素的width
。我只是将其设置为520px
作为示例。
W3Schools说:
居中对齐元素要将块元素(如)水平居中,请使用
margin: auto;
设置元素的宽度将阻止它伸展 到容器的边缘。
然后元素将占用指定的宽度,剩下的就是 空间将在两个边距之间平均分配:
请参阅下面的示例。
.outside {
max-width: 520px;
margin: 0 auto;
}
.square {
float:left;
width: 12.5vw;
height: 12.5vw;
margin-left: 10px;
margin-right: 10px;
position: relative;
border: 0.5px solid red;
text-align: center;
}
.square span {
font-size: 3vw;
}
<div class="outside">
<div class="square">
<span>2.1</span>
</div>
<div class="square">
<span>2.3</span>
</div>
<div class="square">
<span>2.5</span>
</div>
<div class="square">
<span>2.6</span>
</div>
<div class="square">
<span>2.7</span>
</div>
</div>
答案 1 :(得分:0)
我认为最简单的方法是从内部div中删除浮动,并将它们显示为内联块。外部将具有自动边距和中心文本对齐,如下所示:
.outside {
border: 1px solid blue;
text-align: center;
margin: 0 auto;
}
.square {
display: inline-block;
width: 12.5vw;
height: 12.5vw;
margin-left: 10px;
margin-right: 10px;
position: relative;
border: 0.5px solid red;
text-align: center;
}
.square span {
font-size: 3vw;
}
<div class="outside">
<div class="square">
<span>2.1</span>
</div>
<div class="square">
<span>2.3</span>
</div>
<div class="square">
<span>2.5</span>
</div>
<div class="square">
<span>2.6</span>
</div>
<div class="square">
<span>2.7</span>
</div>
</div>
答案 2 :(得分:0)
为text-align
center
outside
.outside{
text-align:center;
}
删除float
&amp;添加display
inline-block
square
.square{
display:inline-block;
width: 12.5vw;
height: 12.5vw;
margin-left: 10px;
margin-right: 10px;
position: relative;
border: 0.5px solid red;
text-align: center;
}
答案 3 :(得分:0)
我完全不了解您的要求,但请尝试以下方法。它将使您的盒子居中,并且在降低分辨率时也不允许它们包裹到下一行。
用以下内容替换你的css:
.square {
float: left;
width: 19%;
height: 12.5vw;
margin-right: 1%;
position: relative;
border: 0.5px solid red;
text-align: center;
box-sizing: border-box;
}
.square span {
font-size: 3vw;
}
.outside {
width: 100%;
}
.inside {
width: 69%;
margin: 0 auto;
overflow: auto;
}
Html with:
<div class="outside">
<div class="inside">
<div class="square">
<span>2.1</span>
</div>
<div class="square">
<span>2.3</span>
</div>
<div class="square">
<span>2.5</span>
</div>
<div class="square">
<span>2.6</span>
</div>
<div class="square">
<span>2.7</span>
</div>
</div>
</div>