简体   繁体   English

如何在包含图标的 div 中居中文本

[英]How to center text in a div, which contains an Icon

I got the following question, with a pic to illustrate:我得到了以下问题,并附上一张图片来说明:

图片

I got a container, containing an icon and text.我得到了一个容器,其中包含一个图标和文本。 The Icon is always on the left, there can be more icons which are all fixed on the left.图标总是在左边,可以有更多的图标都固定在左边。 Now I want the text to be in the centre of the container.现在我希望文本位于容器的中心。 If the text gets too long, it should NOT overlap the icons, but it should expand to the right instead.如果文本太长,则不应与图标重叠,而应向右扩展。

If the text is too long to fit in the container next to the icon, finally I just ellipse it.如果文本太长而无法放入图标旁边的容器中,最后我将其省略。

But how do I do this?但是我该怎么做呢? Is there a css solution?有css解决方案吗?

Thanks in advance!提前致谢!

You can have the text taking the entire width of the container parent, but having left and right padding in a way that it will have enough space for the icon.您可以让文本占据容器父级的整个宽度,但左右填充的方式可以为图标提供足够的空间。

Then you can have the icon overlaying on top of the textbox.然后您可以将图标覆盖在文本框的顶部。

The text box can align text in the center and clip text if overflow.文本框可以将文本居中对齐并在溢出时剪切文本。

I made a simple pen to illustrate the idea.我做了一支简单的笔来说明这个想法。 I hope this help我希望这有帮助

Codepen example代码笔示例

Here's the code.这是代码。

HTML HTML

<div class="container">
  <i class="fa fa-map"></i>
  <div class="textbox"><span class='centerized-text'>This is a centered text and it is very long</span></div>
</div>

CSS CSS

.container {
  background-color: #FAFBFD;
  width: 15rem;
  height: auto;
  padding: 0.5rem;
  border-radius: 4px;
}
i {
  color: teal;
  position: absolute;
}
.textbox {
  padding: 0 1.3rem;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

}
body {
  padding: 2rem;
  background-color: #dedede;
}

(The style for body is just for your visual pleasure) (身体的风格只是为了你的视觉享受)

Here a code这里有一个代码

 #container { display: flex; flex-direction: row; padding: 20px; border: 2px solid skyblue; } #icon { width: 24px; height: 24px; border-radius: 12px; background-color: skyblue; } #text { flex: 1; text-align: center }
 <div id="container"> <span id="icon"></span> <span id="text">Lorem Ipsum</span> </div>

To have text centered in the block使文本在块中居中

 #container { position: relative; padding: 20px; border: 2px solid skyblue; text-align: center; } #icon { width: 24px; height: 24px; border-radius: 12px; background-color: skyblue; position: absolute; left: 20px; top: 0; bottom: 0; margin: auto; }
 <div id="container"> <span id="icon"></span> <span id="text">Lorem Ipsum</span> </div>

In a container use, two span tag and First span will contain your image tab and another has text in it.在容器使用中,两个span tag和第一个跨度将包含您的image tab ,另一个包含文本。

You can use align-text-center to center your text.您可以使用align-text-center

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM