【问题标题】:Flexbox align content in flexed itemFlexbox 对齐项目中的内容
【发布时间】:2021-02-23 03:31:44
【问题描述】:

如何对齐折叠项目中的内容? 顶部的标题和“其余”内容居中?

jsFiddle:https://jsfiddle.net/1wc5kv0d/4/

.row {
    display: flex;
}

.col {
    margin-left: 20px;
    border: 1px solid black;
}

.fixed-width-height {
    width: 40px;
    height: 40px;
    display: inline-block;
    background-color: blue;
    vertical-align: middle;
}

.inline-wrapper>span {
    vertical-align: middle;
}

h3 {
    font-size: 1rem;
}
<div class="row">
    <div class="col">
        <h3>
            title
        </h3>
        <div class="should-center">
            <span>Lorem Ispum</span>
            <span>Icon</span>
        </div>
    </div>
    <div class="col">
        <h3>
            another title
        </h3>
        <div class="should-center">
            <div class="inline-wrapper">
                <div class="fixed-width-height">
                    <span>Name</span>
                </div>
            </div>
        </div>
    </div>
</div>

如何实现标题(h3)保持在顶部和下面的内容应该同样居中。 (Lorem Ipsum 应与“名称”处于同一高度)

是状态:

应该是(忘记那个黑色的笔触,photoshop 挣扎):

【问题讨论】:

  • 您能添加一个视觉所需的输出吗?
  • 是的。在上面添加。

标签: html css


【解决方案1】:

.should-center 和 .col 不是弹性项目。

如果您要创建.should-center display: flex,您可以使用flex-grow: 1 让它增长到100%,然后使用align-items: center; 垂直对齐它们。

我还在.col 中添加了display: flex;,以确保所有孩子都能成长为父母

.col {
    display: flex;
    flex-direction: column;
}

.should-center {
    display: flex;
    flex-grow: 1;
    align-items: center;
}

.row {
  display: flex;
}

.col{
  margin-left: 20px;
  border: 1px solid black;
  display: flex;
  flex-direction: column;
}

.should-center {
    display: flex;
    flex-grow: 1;
    align-items: center;
}

.fixed-width-height{
  width: 40px;
  height: 40px;
  display: inline-block;
  background-color: blue;
  vertical-align: middle;
}
.inline-wrapper > span{
  vertical-align: middle;
}
h3{
  font-size: 1rem;
}
<div class="row">
  <div class="col">
    <h3>
     title
    </h3>
    <div class="should-center">
      <span>Lorem Ispum</span>
      <span>Icon</span>
    </div>
  </div>
  <div class="col">
    <h3>
    another title
    </h3>
    <div class="should-center">
    <div class="inline-wrapper">
        <div class="fixed-width-height">
        
        </div>
        <span>Name</span>
    </div>
    </div>
  </div>
</div>

【讨论】:

  • 不错。谢谢你。在 .col 类上也必须应用 flex-direction: column;。
  • 是的,我确实将它添加到 CSS 本身,认为它不需要单独声明。我已接受您的编辑,这更有意义!谢谢:D
【解决方案2】:

使用这个:

.inline-wrapper > span{
  vertical-align: middle;
    text-align: center;
      padding: 10px;


}
h3{
  text-align: center;
  font-size: 1rem;
  padding: 10px;
  justify-content: space-around;
}

【讨论】:

  • 我不想要周围的空间。我需要 h3 以下的内容以相同的高度为中心。查看入门帖子中的“是”和“应该”状态
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 2018-07-05
  • 2020-08-01
  • 2018-08-21
  • 2015-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多