【问题标题】:CSS text-align property doesn't account for the width of the text itselfCSS text-align 属性不考虑文本本身的宽度
【发布时间】:2014-09-08 16:54:49
【问题描述】:

我正在尝试使用以下代码使标题显示在图像下方的中心:

<div style="float:left;width:100px;" class="dataview">
   <div style="width:100px;height:80px;margin:18px;" class="thumb-wrap">
      <img src="{src}" class="icon" />
      <div style="width:100px;text-align:center;">{text}</div>
   </div>
</div>

然而,最终的结果是文本确实居中,但是将文本的开头放置在 div 的中心,从而使文本显示在右侧。

如何防止这种情况发生?

【问题讨论】:

  • 如果去掉margin:18px;文本在中心正确对齐。您可以为您的图像添加一个容器并将边距放在那里。
  • 谢谢你,它成功了,你可以回答这个问题,所以我可以接受你的回答。
  • 很高兴听到这个消息,不需要添加它作为答案,这是一个简单的技巧!

标签: html css text-align


【解决方案1】:

您可以删除包含文本的div的margin:18pxwidth:100px,因为它的父div已经有width:100px

<div style="float:left;width:100px;" class="dataview">
   <div style="width:100px;height:80px;margin:18px;" class="thumb-wrap">
      <img src="{src}" class="icon" />
   <div style="text-align:center;">{text}</div>
</div>

【讨论】:

    【解决方案2】:

    由于您需要将标题中心保持在图像上,因此组成文本的 div 的宽度应该与 img 的宽度相同。并使文本中心将属性 align='center' 应用于 div 本身,而不是给 css text-align:center

    <img src="{src}" class="icon" />
    <div align="center" style="width:width of image;">{text}</div>
    

    这会解决你的问题

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 2018-01-23
      • 2021-07-01
      • 2018-11-03
      相关资源
      最近更新 更多