如何在图像下方直接对齐文本?

39 html css text justify

我曾经知道如何将图像放在顶部,然后对齐图像下方的文本,使其保持在图像宽度的边界内.但是,现在我不知道该怎么做.这是如何完成的?

Jas*_*son 58

你的HTML:

<div class="img-with-text">
    <img src="yourimage.jpg" alt="sometext" />
    <p>Some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)

如果您知道图像的宽度,那么您的CSS:

.img-with-text {
    text-align: justify;
    width: [width of img];
}

.img-with-text img {
    display: block;
    margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)

否则,图像下方的文字将自由流动.要防止这种情况,只需为容器设置宽度即可.

  • 如果要确保文本居中,可以将css更改为:.img-with-text {text-align:center; } (2认同)

Maj*_*jid 45

您可以使用HTML5 <figcaption>:

<figure>
  <img src="img.jpg" alt="my img"/>
  <figcaption> Your text </figcaption>
</figure>
Run Code Online (Sandbox Code Playgroud)

工作实例.


JBr*_*oks 5

这使图像下方的“A”居中:

<div style="text-align:center">
  <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/opentoselect.gif" />
  <br />
  A
</div>
Run Code Online (Sandbox Code Playgroud)

那是 ASP.Net,它会将 HTML 呈现为:

<div style="text-align:center">
<img id="Image1" src="Images/opentoselect.gif" style="border-width:0px;" />
<br />
A
</div>
Run Code Online (Sandbox Code Playgroud)


Gor*_*son 5

为了能够对齐文本,您需要知道图像的宽度。您可以只使用图像的正常宽度,也可以使用不同的宽度,但 IE 6 可能会对您产生影响而不是缩放。

这是您需要的:

<style type="text/css">
#container { width: 100px; //whatever width you want }

#image {width: 100%; //fill up whole div }

#text { text-align: justify; }    
</style>

 <div id="container"> 
     <img src="" id="image" /> 
     <p id="text">oooh look! text!</p> 
 </div>
Run Code Online (Sandbox Code Playgroud)