【问题标题】:Center a flexbox item in the container, if there is already an item to the left [duplicate]如果左侧已经有一个项目,则将容器中的弹性框项目居中[重复]
【发布时间】:2017-05-16 20:12:41
【问题描述】:

我有一个 flexbox 行容器,其中左侧的 flex 项带有一个未指定宽度的图标,第二个 flex 项是一个多行文本块。

问题是,我希望这个文本位于 flexbox 容器的精确中心,并且此时它被第一个 flex 项推到左侧。

居中的一种方法是将文本框的右侧填充到与图标相同的宽度,例如使用margin-right。

或者我可以在文本上设置一个:after 元素以在右侧添加另一个弹性框?最好的方法是什么?

例如

<div style="display: flex; width: 10em; align-items: center; border:1px solid blue; text-align:center">
<a style="flex: none; width:auto">&rarr;</a>
<a style="flex:1; /* margin-right: how do I make this the same width as the &rarr; box above*/">here <br> is a load of text.<br>I want it to be centered in the div,<br>not shifted to the right</a>
</div>

【问题讨论】:

  • 上一个(现有)问题的答案很好且全面

标签: html css flexbox centering


【解决方案1】:

你想在父块中居中块,这样一个块就不会被计算在内,所以你需要把它从流中取出,设置它position: absoluteThere你可以阅读更多。

【讨论】:

  • 我觉得这个有图标和文字可能重叠的问题。
【解决方案2】:

我会这样做:

<div>
  <a class="a">&rarr;</a>
  <a class="b">here <br> is a load of text.<br>I want it to be centered in the div,<br>not shifted to the right</a>
</div>

 div {
  position relative;
  display: flex; 
  justify-content: center;
  align-items: center; 
  max-width: 22em; 
  height: 22em;
  border:1px solid blue; 

  a.a {
    position: absolute;
    left: 0;
    align-self: center;
  }

  a.b {
    display: flex;
    justify-content: center;
    align-self: center;
    flex: 1;
  }
}

https://jsfiddle.net/km5gdrcm/2/

【讨论】:

  • 这不是将容器中的第二组文本居中更改你的最大宽度为 16em,你会看到。
  • 好吧,我将最大宽度更改为 16em,它仍然居中第二部分
  • 你确定吗? ibb.co/czwbVk
【解决方案3】:

绝对定位图标 a,这会将其从文档流中移除,因此不会影响居中的框。

<div class="container">
<a class="icon">&rarr;</a>
<a class="centered-box">here <br> is a load of text.<br>I want it to be centered in the div,<br>not shifted to the right</a>
</div>

.centered-box {
  flex: 1;
}

.container {
  position: relative;
  display: flex; 
  width: 20em; 
  align-items: center; 
  border:1px solid blue; 
  text-align:center;
}

.icon {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

小提琴:https://jsfiddle.net/nt4shjn5/

在容器中添加填充以避免图标上的文本溢出:https://jsfiddle.net/nt4shjn5/1/

【讨论】:

  • 谢谢。但是,这是否意味着随着容器缩小,文本可能会与图标重叠?
  • 不幸的是,您可以向容器添加填充以阻止这种情况。
  • 查看我发布的第二个小提琴以避免超出图标。
  • 谢谢。但除非我弄错了,否则您已将填充设置为固定宽度,这意味着您必须知道图标的宽度(我不知道)。如果我知道图标宽度,我可以简单地在文本框上设置 padding-right。
  • 这是非常正确的,但您是否希望图标变化如此之大?老实说,我很难想象宽度范围很大的情况。
猜你喜欢
  • 2016-05-16
  • 2017-10-22
  • 2018-03-07
  • 1970-01-01
  • 2020-02-06
  • 2017-08-29
  • 2013-11-05
相关资源
最近更新 更多