html - 多列内容居中
问题描述
我正在创建一个网格类型的布局,其内容将居中,就像这里一样。
.outer {
width: 100%;
height: 100px;
margin-top: 10px;
margin-bottom: 10px;
position: relative;
background: pink;
text-align: center;
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
}
<div class="outer">
<div class="inner">
<h1>I'm Centered</h1>
</div>
</div>
我用过text-align: center;
,但应该有更好的方法来垂直居中内容。我的问题是尝试在其中两个彼此相邻且内容居中的情况下尝试做同样的事情,就像这样;
.outer {
width: 50%;
float: left;
position: relative;
background: pink;
}
@media only screen and (max-width: 500px) {
.outer {
width: 100%;
float: left;
position: relative;
background: pink;
}
}
.inner {
position: relative;
}
.inner-position {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
}
<div class="outer">
<div class="inner">
<div class="inner-position">
<p>I should be centered</p>
</div>
</div>
</div>
<div class="outer">
<div class="inner">
<div class="inner-position">
<p>I should be centered</p>
</div>
</div>
</div>
由于某种原因,它在片段中看起来更糟,但需要这样的东西; 我可以获取列布局,也可以将内容居中。我需要能够同时做到这两点。
EDIT
.container {
width: 100%;
height: 500px;
background: pink;
margin-top: 10px;
margin-bottom: 10px;
}
.col {
width: 50%;
float: left;
position: relative;
}
@media only screen and (max-width: 500px) {
.col {
width: 100%;
float: left;
position: relative;
}
}
.inner {
position: relative;
}
.inner-details {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
}
<div class="container">
<div class="col">
<div class="inner">
<div class="inner-details">
<h1>Middle 1</h1>
</div>
</div>
</div>
<div class="col">
<div class="inner">
<div class="inner-details">
<h1>Middle 2<h1>
</div>
</div>
</div>
</div>
解决方案
我希望这是你的愿望输出。请检查代码片段。
* {
box-sizing: border-box;
}
.outer {
width: 50%;
height: 100px;
float: left;
position: relative;
background: pink;
margin: 10px 0;
}
@media only screen and (max-width: 500px) {
.outer {
width: 100%;
}
}
.inner {
position: relative;
width: 100%;
height: 100%;
}
.inner-position {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="outer">
<div class="inner">
<div class="inner-position">
<p>I should be centered</p>
</div>
</div>
</div>
<div class="outer">
<div class="inner">
<div class="inner-position">
<p>I should be centered</p>
</div>
</div>
</div>
推荐阅读
- xpath - xpath:提取节点的尾随文本
- amazon-web-services - 有一种方法可以按堆栈列出导出值
- angular - Angular 自定义验证器静默失败/不触发
- python - 如何修复我的查询中的 Python F 字符串,使其不易受到 SQL 注入的攻击?
- orleans - Orleans.NET 中的 IHttpClient 实现
- angular - 使用 Angular 自定义 Web 组件会引发错误:选择器“app-root”不匹配任何元素
- rust - 如何在 Rust 中将 SystemTime 转换为 ISO 8601?
- c - 从C中的字符串中删除非字母数字字符
- bluetooth - 在 yocto 构建的 defconfig 上“禁用”后,蓝牙仍然出现在启动列表中
- object - 如何从 obj 文件中删除除一种颜色之外的所有颜色