我是编程的新手。我已经水平对齐了 5 个盒子,但我想要的是将盒子居中。这些盒子也应该响应它们现在的样子。我正在寻找如何使div居中,但结果我得到了 margin: 0 auto; width: 800px;
.当我将浏览器调整为 100% 时,第 5 个框位于其他框下方。
.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>
我认为最简单的方法是从内部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>
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>
outside
添加text-align
center
.outside{
text-align:center;
}
删除float
并添加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;
}
我不完全理解您的要求,请尝试以下操作。它将使您的盒子居中,并且不允许它们在降低分辨率时换行到下一行。
将您的 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:
<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>