【问题标题】:Center text and image居中文本和图像
【发布时间】:2014-09-27 14:10:27
【问题描述】:

我正在尝试将页面中的文本块居中,并在文本块中放置水平和垂直居中的图像。我不想使用背景图片。

这是我得到的,但根本不起作用。

<div style="font-family: Times; font-size: 12pt; width: 400px; position: absolute; z-index:20; margin-left:auto; margin-right:auto; top: 50px;">
    <img style="position: absolute; z-index:1; top: 20px; margin-left:auto; margin-right:auto;" src="MyImage.jpg" width="202" height="267" />
        <strong>This is my Text. Blah Blah Blah Blah Blah Blah
        <br />
        Blah Blah Blah Blah Blah Blah
        <br />
        Retrieved from:<br />
        Blah Blah Blah Blah Blah Blah
        <br />
        Blah Blah Blah Blah Blah Blah
        <br />
</div>

【问题讨论】:

  • 你希望图片在文字后面,对吧?
  • 是的。文字背后的图像。

标签: html css


【解决方案1】:

我读过一篇关于此的文章。要完美对齐块,请使用:

.Center-Container {
  position: relative;
}

.Absolute-Center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

这些 CSS 样式是关键!在这里查看:

div {
  font-family: Times;
  font-size: 12pt;
  width: 400px;
  height: 200px;
  z-index: 20;
  margin-left: auto;
  margin-right: auto;
  top: 50px;
  background-color: red;
}
p {
  position: relative;
}
img {
  z-index: 1;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
<div>

  <p>
    B lah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah
    Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah

    <br />
    <img src="MyImage.jpg" width="50" height="50" />
  </p>

</div>
您可以在此处阅读有关此内容

http://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/

编辑

img 标签现在位于 p 标签中。你可以在这里查看Should I put paragraph tags around images? 如果这是个好主意。

【讨论】:

  • 文字居中,但图片不居中。我希望图像在文本中居中。
  • 这是您要找的吗?我编辑了 sn-p
  • 您能选择我的答案作为正确答案吗? :) 所以其他人会知道这是正确的答案! :)
【解决方案2】:

位置:相对;

而不是绝对的 http://codepen.io/anon/pen/hsBux

<div style="font-family: Times; font-size: 12pt; width: 400px; position: relative; z-index:20; margin-left:auto; margin-right:auto; top: 50px;">
<img style="position: absolute; z-index:1; top: 20px; margin-left:auto; margin-right:auto;" src="MyImage.jpg" width="202" height="267" />

 <strong>This is my Text. Blah Blah Blah Blah Blah Blah
    <br />
    Blah Blah Blah Blah Blah Blah
    <br />
    Retrieved from:<br />
    Blah Blah Blah Blah Blah Blah
    <br />
    Blah Blah Blah Blah Blah Blah
    <br />
 </div>

【讨论】:

  • 图像在文本的左边距。我希望它从文本块水平和垂直居中。
  • 抱歉没看错。似乎答案 2 应该可以完成这项工作。祝你好运
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-24
  • 2020-10-11
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
相关资源
最近更新 更多