【问题标题】:Match the height of the parent to the child element - relative and absolute position [duplicate]将父元素的高度与子元素匹配 - 相对和绝对位置
【发布时间】:2017-12-10 17:03:46
【问题描述】:

虽然这看起来很基本,但我无法让它工作。

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

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

这是我正在查看的 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;
}

【问题讨论】:

标签: html css


【解决方案1】:

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

.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;
}
<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>

【讨论】:

  • 嗨.. 谢谢你的回复。这与我想要的很接近。但。如果父级有填充,我该如何使用它。我仍然需要孩子覆盖父母的整个高度(因此我最初使用绝对位置)。
  • 将填充值作为负边距添加到您的孩子,当然只添加到上/右/下侧。
  • 是的.. 完全尝试过.. 但是由于某种原因,当子项的宽度为 0px 时,父项变得太长。但是回到正常高度,当我在隐藏的 css 中执行 display:none; 时。但后来我失去了我正在使用的过渡(在点击另一个元素时将子窗口切换为 0px 和 30px 宽度)
  • 子项的宽度不会影响其高度,父项的高度仍然被清除。这可能是关于过渡的另一个问题。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多