使用CSS控制figcaption在图形中相对于响应图像的位置

时间:2018-07-17 18:35:30

标签: html css figure

我正在组建一个网站,该网站需要显示一个响应图像,其中图像始终在浏览器顶部对齐,并且标题固定在紧靠图像下方并与图像左边缘对齐的位置。

我的图像表现完美,但是除了相对于人物外,我无法控制figcaption的位置。如何相对于图像控制figcaption?我想发生的事情是使无花果标题立即在图像的左下方对齐并在其左边缘对齐(不对齐中心)。它似乎总是在图的底部结束。我已经读了约25篇文章,试图找出如何做到这一点。

谢谢!

这是我的HTML

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>

<link href="test02.css" rel="stylesheet" type="text/css">
</head>

<body>

    <figure class="niag">
        <img class="hero" src ="Images/IMG_5678.jpg" alt=""/>
        <figcaption>This is one of my nicest images</figcaption>
    </figure>

</body>
</html>

这是我的CSS

.niag {
/*      display: block;*/
    position: relative;
    height: auto;
    border: 1px dotted gray;    
    }
.niag figcaption {

    border: 1px dotted blue;
    position: absolute;
/*    bottom: 0;*/
    left: 0;
    right: 0;
    }
.hero {
    display: block;
    height: 85vh;
    width: 100%;
    object-fit: contain;
    object-position: top;
    }

2 个答案:

答案 0 :(得分:0)

尝试top:100% + margin-bottom

想法演示

* {
  margin:0
}
.niag {
  position: relative;
  height: auto;
  border: 1px dotted gray;
  margin-bottom: 1.5em;/* update*/
}

.niag figcaption {
  border: 1px dotted blue;
  position: absolute;
  top: 100%;/* update*/
  left: 0;
  right: 0;
}

.hero {
  display: block;
  height: 85vh;
  width: 100%;
  object-fit: contain;
  object-position: top;
}
<figure class="niag">
  <img class="hero" src="http://dummyimage.com/1200x600" alt="" />
  <figcaption>This is one of my nicest images</figcaption>
</figure>
next-content

如果要在图像的bottom left上设置文本,则不要使用object-fit,其中img标签和视觉对象可能不会覆盖同一区域,并保持比例,则可以使用max-heightdisplaymargin

* {
  margin:0
}
.niag {
  position: relative;
  border: 1px dotted gray;
  margin:0 auto  1.5em;/* update*/
  display:table;
}

.niag figcaption {
  border: 1px dotted blue;
  position: absolute;
  top: 100%;/* update*/
  left: 0;
  right: 0;
}

.hero {
  display: block;
  max-height: 85vh;
  max-width:100%;
}
<figure class="niag">
  <img class="hero" src="http://dummyimage.com/1200x600" alt="" />
  <figcaption>This is one of my nicest images</figcaption>
</figure>
next-content

必须做出一些妥协或保留经过精心考虑的javascript代码段来处理您的第一个目标

答案 1 :(得分:0)

您可以将网格布局用于图像的自动调整大小和标题与图像的对齐:

.niag {
    display: grid;
    grid-template: ". image    ."
                   ". caption  ."
                   /   1fr auto 1fr;
    border: 1px dotted gray;    
    }
.niag figcaption {
    grid-area: caption;
    border: 1px dotted blue;
    }
.hero {
    grid-area: image;
    display: block;
    height: 85vh;
    }
<figure class="niag">
   <img class="hero" src ="http://placekitten.com/800/900" alt=""/>
   <figcaption>My image</figcaption>
</figure>