首页 > 解决方案 > 多列内容居中

问题描述

我正在创建一个网格类型的布局,其内容将居中,就像这里一样。

.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>

标签: htmlcss

解决方案


我希望这是你的愿望输出。请检查代码片段。

* {
  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>


推荐阅读