首页 > 解决方案 > HTML 中心图像和下面的文本段落

问题描述

我想在浏览器中显示一个图像,该图像下方还有一大段文字。我希望图像下方显示的文本与图像的左右边界对齐。图像来自外部服务 API,并且每天都在变化,有时是横向的,有时是纵向的。我已将图像尺寸减小到 75%,以便它更适合屏幕。

想象一下“我”是图像,“T”是文本段落:

          IIIIIIIIIIIII
          IIIIIIIIIIIII
          IIIIIIIIIIIII

          TTTTTTTTTTTTT
          TTTTTTTTTTTTT
          TTTTTTTTTTTTT
          TTTTTTTTTTTTT

使用表格和一些格式,我有一些几乎合理的外观,但我不相信这是最好的解决方案。我正在寻找比我更好的清洁方法。此外,我搜索了网络和堆栈溢出,并没有遇到任何迄今为止真正有效的解决方案。

我当前的代码(注意图像和文本的 Angular 变量):

<h1 class="page-title">Nasa Daily Image</h1>
<br>

<div>
<p style="text-align: center;">{{_nasaImage._title}}</p>

 <div style="width: 95%; margin:0 auto; display: block;">
    <table  style="border:1px solid black; width: 95; margin-left: auto; margin-right: auto;">
        <tr>
            <td style="text-align: center;"> 
                <img style="height: 75%; width: 75%;" src={{_nasaImage._imgUrl}}  alt="link broken?" >
            </td>
        </tr>
        <tr>
            <td>                    
                <p style="margin-left: 105px; margin-right: 105px; text-indent: 50px;"> {{_nasaImage._explanation}}</p>
            </td>
        </tr>

    </table>
</div>
<div>

图像和文本的布局将与此类似: 堆积在文字上的图片

附加信息:这是针对 Angular 项目的。代码由 app.component.html 在“jumbotron”div 中呈现,如下所示:

   <!-- main content container -->
 <div class="jumbotron">
  <div class="container">
      <div class="row">
            <div class="col-sm-12">
              <router-outlet></router-outlet>
            </div>
      </div>
  </div>
     </div>

标签: htmlcssangularimagetext

解决方案


你只需要一些CSS来做到这一点。这是Stackblitz 上的一个示例,这里是代码(使用新信息编辑):

Displayer 组件(它将显示图像和文本(当然可以作为输入传递):

.html:

<div class="displayer">
    <img src="https://picsum.photos/300/200" />
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras pellentesque ornare leo, vel eleifend ante rutrum ac.
    </div>

.css:

.displayer {
  display: inline-block;
  width: 75%;
  height: auto;
  text-align: justify;
  background-color: transparent;
}

img {
  width: 100%;
  height: auto;
}

应用组件:

.html:

<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-sm-12 text-center">
                <h1>NASA DAILY IMAGE</h1>
                <p>Title of the image like "Eclipse under the Bamboo"</p>
                <app-displayer></app-displayer>
            </div>
        </div>
    </div>
</div>

请注意,是 App 组件负责app-displayertext-center(A 引导类)的水平对齐。

这是您在浏览器中的结果: 代码结果(在 stackblitz repro 中也可见)


推荐阅读