带有标题

时间:2016-06-14 20:38:46

标签: html css image

我在为缩小包装的div添加标题时遇到了一些问题,该div的宽度由图像提供。

问题是,我希望用户通过PHP设置图像的宽度,这反过来会影响父div的宽度。

<div class="shrinkwrap">
   <img src="image.jpg" width="$width">
</div>

.shrinkwrap {
    display: inline-block;
    border: 1px solid #FFF;
}

这个有用的技巧对我有用,但是当我想为图像添加标题,并且标题超出图像的宽度时,它会推动父div的宽度。

我已尝试使用此标题(定位,弹性盒等)的不同方法,但由于收缩包装容器将占用其子女的宽度,如果标题最宽,则会影响整体看起来这个。

设置容器div的宽度并给出100%宽度的图像是一个快速的解决方案,但为了使其动态,我不得不使用内联样式,这不是很好。

任何帮助将不胜感激!

HTML:

<div class="shrinkwrap">
<img id="version1" src="http://placehold.it/520x320" width="320px" alt="" />

  <div class="caption">
     Lorem ipsum dolor sit ius ex admodum consequuntur, te dicunt epicurei invenire eum, te ius vocent eligendi. Sed unum persecuti te, tempor nostrud disputationi eos ad. ius ex admodum consequuntur, te dicunt epicurei inv!
  </div></div>

CSS:

.shrinkwrap { 
   border: 1px solid red;
   display: inline-block;
}

#version1 {
    display: block;
    max-width: 100%;
}

.caption {
  text-align: center;
  border-top: 1px solid red;
  padding: 10px;
}

http://jsfiddle.net/nx39rkev/49/

1 个答案:

答案 0 :(得分:0)

您可以使用javascript实现此目的。这是使用jQuery的片段:

此处位于jsfiddle

var imgSetByUser = $("img");

imgSetByUser.each(function(){

var thisImgWidth = $(this).width();
$(this).parent().css("max-width",thisImgWidth);

});
.shrinkwrap { 
   border: 1px solid red;
   display: inline-block;
}

#version1 {
    display: block;
    max-width: 100%;
}

#version2 {
    display: block;
    width: 100%;
}

.caption {
  text-align: center;
  border-top: 1px solid red;
  padding: 10px;
}

.full {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Exact pixel length, no percentage --> 
<!-- Full width can be set as a class -->

<div class="shrinkwrap">

  <img id="version1" src="http://placehold.it/520x320" width="320px" alt="" /> <!-- % is relative to parent-->

  <div class="caption">
     Lorem ipsum dolor sit ius ex admodum consequuntur, te dicunt epicurei invenire eum, te ius vocent eligendi. Sed unum persecuti te, tempor nostrud disputationi eos ad. ius ex admodum consequuntur, te dicunt epicurei inv!
  </div>

</div>


<br/><br/><br/>

<!-- Full width percentage and pixel length -->
<div class="shrinkwrap" style="width:500px">
    <img id="version2" src="http://placehold.it/520x320" alt="">
    <div class="caption">Lorem ipsum dolor sit amet, ius ex admodum consequuntur, te dicunt epicurei invenire eum, te ius vocent eligendi. Sed unum persecuti te, tempor nostrud disputationi eos ad. ius ex admodum consequuntur, te dicunt epicurei invenire eum, te ius vocent eligendi. Sed unum persecuti te, tempor nostrud disputationi eos ad.</div>
</div>