带有固定大小div的文本标题的图像

时间:2015-11-04 09:48:58

标签: javascript jquery html css image

我遇到了CSS / HTML问题,

我有一个固定大小的div,我希望有一个文本(在图像的顶部或底部)和里面的图像。

必须遵守图像比例,并且事先不知道图像的宽度和高度。

我尝试了很多东西,我得到的最好的结果是文字,我的图像保留了比例,但是图像被剪裁了。

以下是我的问题的说明:

HTML结构:

The HTML structure

主要部门:

enter image description here

包含文字的div:

enter image description here

img元素(我们可以看到图像被裁剪):

enter image description here

图像被裁剪,因为它占用了父div的宽度,但是文本div也包含在父div中,所以需要一些地方......

编辑:只是为了精确的东西:我用javascript动态添加这些元素,所以当我设置大小时,div和图像还没有在DOM中(所以我不能得到文本div大小来计算img尺寸)。

解决方案是什么?

谢谢:)

编辑2:

我想要的是什么:

enter image description here

编辑3:生成div的javascript代码:

    this.m_cellElem = document.createElement('div');
    this.m_cellElem.style.width = width + "px";
    this.m_cellElem.style.height = height + "px";

    var text = document.createElement('div');
    text.style.width = width + "px";
    text.style.textAlign = "center";
    text.innerHTML = this.m_name;

    this.m_imgElem = document.createElement('img');
    this.m_imgElem.id = "viewImg-" + this.m_viewUniqueId;
    this.m_imgElem.setAttribute('src', 'data:image/png;base64,' + this.m_poster);
    this.m_imgElem.style.maxWidth = "100%";
    this.m_imgElem.style.maxHeight = "100%";

    this.m_cellElem.appendChild(text);
    this.m_cellElem.appendChild(this.m_imgElem);

3 个答案:

答案 0 :(得分:1)

首先确保父div没有任何'overflow:hidden'属性。

设置内部div样式

display: inline-block;
width: 100%;
text-align: center;

并且图像最大高度不应为100%; 它应该是'父div高度 - 文本div高度'。 例如, 考虑父div高度100px和文本div高度30px然后图像样式应

display: inline-block;
max-width: 100%;
max-height: 70px;

试试这个,希望它能起作用!!!

<强> Editted

按照这个工作链接,我希望这是你所期待的。 jsfiddle

答案 1 :(得分:0)

min-height用于您的父div,而不是height

<div style="width:276px;min-height:58px;">

答案 2 :(得分:0)

最后感谢Antony SUTHAKAR J。

我刚刚调整了他的代码:

$('body').on('DOMNodeInserted', '.container', function(e) {
var mainDivs = e.target.getElementsByClassName("mainDiv");

    for (var i = 0; i < mainDivs.length; i++) {
        var mainDiv = mainDivs[i];
        var img = view.getElementsByClassName("img")[0];
        var text = view.getElementsByClassName("textDiv")[0];
        var imgHeight = $(view).height() - $(text).height();
        img.style.maxHeight = imgHeight + "px";
    }
});

效果很好。谢谢安东尼。