如何将<img>的高度设置为<h1>的高度?

3

我希望将<img>的高度设置为使用<h1></h1>的高度。

例如:如果<h1></h1>的高度为10em,则我也希望<img>的高度为10 em。
但问题是我不知道每个Web浏览器上<h1></h1>的确切高度。

我尝试以百分比设置<img>的高度,但这样并没有起作用。我该怎么办?

以下是我的原始代码:

 <div class="row" style="margin-top: 1%;">
    <div class="large-9 columns">
        <h1><img src="img/UnionJR.png"> <a href="subjectlist.html#BrE" class="logo">English</a></h1>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
        </p>
    </div>
    <div class="large-3 columns">
        <img src="http://placehold.it/350x150&text=Img">
    </div>
</div>

谢谢

6个回答

2

我尝试了这个方法,对于Chrome浏览器来说有些效果。(我没有试过其他浏览器)

<h1><img src="img/UnionJR.png" style="height: 1em;"> <a href="subjectlist.html#BrE" class="logo">English</a></h1>

看起来这种方法解决问题的方式不太好,但对于简短的工作来说,它还是可行的。

无论如何,我仍然想知道其他方法。请添加更多!


1
除非我在这里漏掉了什么,如果您的h1设置了特定的高度,例如

h1 {
  height: 10em;
}

你应该能够使用

标签。
h1 img {
  height: 100%;
}

百分比高度只有在其父元素设置了具体高度时才有效。我在Chrome中尝试过,它可以正常工作-图像将采用h1的高度。
 <html>
 <body>

 <div class="row" style="margin-top: 1%;">
    <div class="large-9 columns">
        <h1><img src="http://placehold.it/350x150&text=Img"> <a href="subjectlist.html#BrE" class="logo">English</a></h1>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
        </p>
    </div>
    <div class="large-3 columns">
        <img src="http://placehold.it/350x150&text=Img">
    </div>
</div>

<style>
    h1 {
        height: 10em;
    }
    h1 img {
        height: 100%;
    }
</style>

 </body>
 </html>

1

我知道这个问题很旧了,但是我想回答一下,为了那些像我一样在寻找解决方案的人。

我发现一个可行的解决方案是使用这个CSS。

.imgh1 {
background-image: image.png;
background-repeat: no-repeat;
background-size: contain;
}

将其应用到您的标题中,如下所示:

<h1 class="imgh1">&nbsp;</h1>

0
我建议为 <h1><img> 标签都设置一个类。可以这样做:
<h1 class='tall'>
  <img class='tall' src="img/UnionJR.png"> 
  <a href="subjectlist.html#BrE" class="logo">English</a>
</h1>

带有样式:

.tall {
  height: 800px;
}

请记住,使用 em 单位意味着嵌套元素(如果高度使用 em 定义)将乘以其父元素的高度。因此,如果您的标题为 10 em,而您的 img 也是 10 em,则图像实际上将显示为 100em 或高度(10x10)。
在这种情况下,我建议使用基于像素的高度,因为它不会像 em 那样复合

0
你可以在CSS文件中添加一些规则来针对特定的浏览器并覆盖原本应用的任何样式:
h1 {
    -webkit-margin-before: 0em;
    -webkit-margin-after: 0em;
}

0
你可以为 <h1> 标签使用固定高度,并将 height: inherit; max-height: 100%; min-height: 100%; 应用于图像,以始终保持它们的相同高度。只需注意,您的图像应具有特定尺寸,以避免在应用最小和最大高度样式时出现模糊。
img {
    height: inherit;
    max-height: 100%;
    min-height: 100%
}
h1 {
    height: 50px;
}

DEMO


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接