将父级的高度与子元素匹配 - 相对位置和绝对位置

时间:2016-04-18 09:25:27

标签: html css

尽管看起来很基本,但我无法使其发挥作用。

简单地说,我有一个父元素 - 相对位置。 然后是一个子元素 - 绝对位置。

如果孩子的身高高于父亲的身高,我该如何匹配父亲的身高。意思是,如何让父母扩展。

这是我正在看的js小提琴 https://jsfiddle.net/wthwawcv/

<div class="parent">
  dsfsdfsdfsdf<br> 
  hellow .. line 2 <br>
  hello .. line 3
  <div class="child">
    this is the child element to be diaplayed
  </div>
</div>


.parent {
  width:100%;
  background: #ff0000;
  width:200px;
  position: relative;
  overflow: hidden;
}

.child {
  width:40px;
  height:100px;
  background: #ffff00;
  position: absolute;
  right: 0;
  top: 0;
}

2 个答案:

答案 0 :(得分:1)

而不是绝对定位,你可以使用float和clearfix hack:

&#13;
&#13;
.parent {
  width:100%;
  background: #ff0000;
  width:200px;
  position: relative;
}
.parent:after {
  content: '.';
  color: transparent;
  clear: right;
  overflow: hidden;
  display: block;
  height: 0;
}

.child {
  float: right;
  width:40px;
  background: #ffff00;
}
&#13;
<div class="parent">
<div class="child">
    this is the child element to be displayed
  </div>
  Child is<br> 
  longer than<br>
  parent content.
</div>
<br>
<div class="parent">
<div class="child">
    child
  </div>
  Child is<br> 
  shorter than<br>
  parent content.
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您可以使用jquery,请在您的文件中添加以下代码并从子类中删除高度。 这是工作FIDDLE DEMO

var min_parent_height = jQuery(".child").height()+"px";
console.log(min_parent_height);
jQuery(".parent").css({'min-height':min_parent_height});
相关问题