html - 如何使我的文本和第一个 div 垂直对齐?
问题描述
所以我正在做这个代码来训练,但我找不到将我的文本与我的 div 框对齐的方法。此外,我还试图使包含其他所有内容的 div 也与页面垂直对齐的代码。
body{
background-color: black;
}
.box{
border-style: solid;
width: 240px;
height: 240px;
margin: auto;
}
.boxInside{
border-style: solid;
width: 90%;
height: 90%;
margin: auto;
padding: 0px;
/* align a div vertically within its parent element */
position: relative;
top: 50%;
transform: translateY(-50%);
}
p{
text-align: center;
}
<div class="box" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div class="boxInside" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div class="boxInside" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div class="boxInside" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div class="boxInside" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div style="">
<p>Testing Display</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
解决方案
始终使用 css flex
ORgrid
属性。
body{
background-color: black;
}
/* I used flex property */
.box{
border-style: solid;
width: 240px;
height: 240px;
margin: auto;
display: flex;
justify-content:center;
align-items:center;
}
.boxInside{
background-color:blue;
padding:9px;
}
.boxInside > p{
text-align:center;
}
<div class="box" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div class="boxInside" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div class="boxInside" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div class="boxInside" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<div class="boxInside" style="background-color: white;">
<div class="boxInside" style="background-color: gray;">
<!--small change here -->
<!--common class added here-->
<div class="boxInside">
<p>Testing Display</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
注意: 如果你想要深盒子错觉,那么将 padding 从px
变为%
。
推荐阅读
- javascript - 使用 JavaScript (Ember.js) 将类型 ID 与 TMDb 中的类型名称匹配
- python - 在 selenium 中使用 css 选择器/xpath 获取数据时遇到问题
- angular - Angular trackBy 不能在嵌套 *ngFor 中工作
- flutter - 如何在继续时修改 Step StepState
- prometheus - 我们可以在不同的机器上使用 prometheus 和 node_exporter
- android - 如何格式化蓝牙打印机的文本?
- hyperledger-fabric - HyperLeder Fabric:无法调用链代码名称:“lscc”,错误:启动链代码时超时已过期
- java - java中Ejb项目中的流执行
- ruby-on-rails - 如何使用带有多个嵌套模型的 form_for 在表单上呈现错误
- java - 有什么方法可以一次获取 50 件物品,然后再获取下 50 件及以后的物品?