html - CSS中心div
垂直和水平到父 div
问题描述
我有以下 HTML/CSS,我尝试在其中将 adiv
与<p>
它们的父div
包装器居中。我尝试使用众所周知的translate(-50%, -50%)
解决方案,但它不起作用。我也试过用margin: 0 auto
,也没有成功。我想我错过了一点,但我不明白。有人可以告诉我吗?
提示:这是一个仅由相关的 HTML 和 CSS 规则构成的 MCVE,还有很多,所以不要混淆一些display:block
或!important
. 我为背景和边框上色以获得更好的可视化效果。
这是片段:
.half-width {
width:50%;
height: 795px;
}
div, p {
border: 1px solid red;
}
.container {
font-family: 'IBMPlexSans';
}
.container > div {
box-sizing:border-box;
border: 1px solid green;
background-color: inherit;
}
.container{
display:flex;
padding: 0;
width: 100%;
background-color: aqua;
flex-wrap: nowrap;
flex-direction: column;
}
.mobile-only{
display: block;
width: 100%;
}
/** for switching between mobile and desktop rules **/
.desktop-only{
display: none;
}
.background-black{
background-color: #4E4E4E !important;
width: 650px !important;
border-radius: 20px;
}
.size-35{
font-size: 35px;
height: 526px;
text-transform: uppercase;
}
.size-25{
font-size: 25px;
width: 335px;
height: 95px;
}
.size-19{
font-size: 19px;
width: 335px;
height: 350px;
margin-top: -25px;
}
/** center container div to an unknown body, works fine **/
.center-to-bg{
margin-left: auto;
margin-right: auto;
}
.height-495{
height: 495px;
}
.height-526{
height: 526px;
}
.desc-text > p{
display: block;
}
/** center the content div with the text to its parent,
horizontally AND vertically, does not work**/
.center-text{
position: relative;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.center-text > p{
display: block;
}
.center-h{
display: block !important;
left: 50%;
}
.half-width{
width: 100vw;
}
<div class="container">
<div class="half-width mobile-only background-black height-526 center-to-bg">
<div class="center-text color-white size-35" id="section2">
<p>ThIS IS </p>
<p>Á PARAGRAPH</p>
</div>
</div>
<div class="half-width mobile-only center-to-bg">
<div class="center-text color-white size-19">
<div class="desc-text">
<p>This is a long text that needs to be centered over multiple lines</p>
<p>
Because mobile devices are not that width
</p>
</div>
</div>
</div>
</div>
解决方案
当您将元素居中在父级中时,您可以给父级:
显示:表格;高度:100vh;
和孩子:
垂直对齐:中间;显示:表格单元格;
.outer {
display: table;
height: 100vh;
width: 100vw;
background: yellow;
}
.inner {
vertical-align: middle;
display: table-cell;
background: red;
}
<div class="outer">
<div class="inner">
Inner div text.
</div>
</div>
推荐阅读
- python - 在大文件的内容中获取一行
- delphi - 如何初始化我的自定义 IdIOHandler 字段?
- rust - 将结构转换为特征
- laravel - TinyMCE 5的文件管理器不显示上传的图像,找不到404图像,但它存在于文件夹中 - Laravel
- java - 如何将数据推送到firebase?
- css - 使用复选框默认显示/隐藏以使用纯 CSS 隐藏
- javascript - Discord .setImage 文件不在嵌入中,而是在它之前发送
- python - 如何使用 norm.ppf() 查找 z 值?
- spring-boot - Spring Boot 2 使用 Webflux、Netty 和 HTTP2,导致证书无效,可能配置错误
- r - 使用操作按钮重置复选框组