【问题标题】:Two <div> "columns" within a parent <section>, trying to vertically center the right-hand div relative to the parent.父 <section> 中的两个 <div> “列”,试图使右侧 div 相对于父级垂直居中。
【发布时间】:2018-01-08 19:48:05
【问题描述】:

我有一个包含两个 div,它们形成两个“列”,类名为 context_left 和 context_right。左侧列 div 的高度大于右侧的高度。左侧列的宽度为 30%,右侧列的宽度为 45%。右侧列 div 是右浮动的。如果我删除右边的浮动或降低宽度,右边的 div 列就会消失。

父级没有定义的高度。如何让右手相对于父高度垂直对齐?

HTML 代码

<section>
        <div class="content context_left">
              <p>Lorem Ipsum (This is actually a long paragraph)</p>
              <p>Lorem Ipsum (So is this one) </p>
              <p style="padding: 5%;">
                        <b>Foo Bar</b>
                    </p>
                    <p>
                        Lorem Ipsum (long paragraph 3)
                    </p>
                </div>
                <div class="context_right">
                    <img src="foo.svg" alt="bar" id="logo">
                </div>
            </section>

CSS 代码:

section {
overflow: hidden;
}

.context_left{
    display: inline-block;
    width: 30%;
    margin-left: 10%;
    overflow: hidden;
    float: left;
    text-align: left;
    vertical-align: middle;
    font-family: 'Lato';
    font-weight: 300;
    font-size: medium;
} 

.context_right{
    display: inline-block;
    height: 300px;
    float: right;
    line-height: 300px;
    width: 45%;
    padding-right: 10%;
}  /* This is the one I'm trying to vertically align relative to <section> */

我尝试过的:

--将父级显示为表格,子级显示为表格单元格并设置垂直对齐为中间 --将父子显示设置为带有vertical-align的inline-table --尝试在父级上使用 display: flex 创建一个弹性框,然后我可以垂直对齐 --定义父级的高度以便我可以使用vertical-align(没关系,没用) --改变字体大小 --将位置设置为绝对(可怕的重叠元素)

我不能使用绝对定位或额外的填充,因为它在移动设备上看起来很糟糕。另外,使用 top: 50% 似乎将其推得比左侧列的高度定义的高度的一半还要远,因此它不是一个可以缩放的相对选项。 S.O. 是什么意思?推荐?

【问题讨论】:

  • 可以选择 JavaScript 吗?如果没有,你会想试试我不太熟悉的 flexbox。

标签: html css vertical-alignment


【解决方案1】:

你的意思是这样的:

section {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-pack: distribute;
  justify-content: space-around;
}

section>div {
  border: 1px solid;
}

section>div:nth-child(1) {
  -webkit-box-flex: 0.3;
  -ms-flex: 0.3;
  flex: 0.3;
}

section>div:nth-child(2) {
  -webkit-box-flex: 0.45;
  -ms-flex: 0.45;
  flex: 0.45;
  -ms-flex-item-align: center;
  -ms-grid-row-align: center;
  align-self: center;
}


/* This is the one I'm trying to vertically align relative to <section> */
<section>
  <div class="content context_left">
    <p>Lorem Ipsum (This is actually a long paragraph)</p>
    <p>Lorem Ipsum (So is this one) </p>
    <p>
      <b>Foo Bar</b>
    </p>
    <p>
      Lorem Ipsum (long paragraph 3)
    </p>
  </div>
  <div class="context_right">
    <img src="foo.svg" alt="bar" id="logo">
  </div>
</section>

【讨论】:

    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 2018-04-25
    相关资源
    最近更新 更多