使用绝对位置将行拟合到超大内容

时间:2016-01-12 12:00:32

标签: javascript css twitter-bootstrap

以下是一行(在行列表中)的示例,其中一行项超出了其高度。

设置overflow: visible并未解决此问题,因为它仅在不调整外部DIV大小的情况下使内容可见,因为position: absolute已设置。

如何使行(绿色边框)适应其内容?

它使用Bootstrap的一些CSS类,理想情况下应该使用现有的类。

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.css" rel="stylesheet">

<div class="form-group panel-heading row" style="display: block; position: relative; line-height: 20px; border: 1px solid green">
  <div class="col-sm-2 switch-wrapper" style="overflow:visible; position:relative; border: 1px solid blue">
    <div style="overflow:visible; border: 1px solid yellow">
      <i class="fa fa-caret-up" style="border: 1px solid black"></i><span style=" position: absolute;margin-left: 5px; border: 1px solid red">A long description adjacent to the input field that doesn't fit into one line and it has to be broken into multiple lines.
    </span></div>
	</div>
</div>

1 个答案:

答案 0 :(得分:1)

当一个元素是绝对元素时,它不在&#34;渲染流程中,被其他元素忽略。因此,您无法根据绝对元素更改父div的大小。但是你总能找到JavaScript解决方案。

&#13;
&#13;
$(document).ready(function(){
//Initially set parent height = child height
$('.parent').height($('.child').height());
//set parent's height = child's height when window resizes
$(window).on('resize', function (){
    $('parent').height($('child').height()); 
})
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.css" rel="stylesheet">

<div class="form-group panel-heading row parent" style="display: block; position: relative; line-height: 20px; border: 1px solid green;padding-bottom:5px;">
  <div class="col-sm-2 switch-wrapper" style="overflow:visible; position:relative; border: 1px solid blue">
    <div style="overflow:visible; border: 1px solid yellow">
      <i class="fa fa-caret-up" style="border: 1px solid black"></i><span class="child" style="position: absolute;margin-left: 5px; border: 1px solid red">A long description adjacent to the input field that doesn't fit into one line and it has to be broken into multiple lines.
    </span></div>
	</div>
</div>
&#13;
&#13;
&#13;