如何使用absolutley position子元素具有响应高度

时间:2015-07-09 13:48:39

标签: javascript jquery css

我做了一个非常基本的引用“carousel”,通过一次一个地显示元素,在网站上显示客户引用。

引号绝对位于容器内部,然后相应地显示。如何使父容器成为最高报价(加上填充)的高度而不必在容器上放置固定的像素高度,因为从技术上讲,父容器现在是空的。仅限css。

<div class="parent-container">
    <div class="quote child-element">Lorem Ipsum</div>
    <div class="quote child-element">Lorem Ipsum</div>
    <div class="quote child-element">Lorem Ipsum</div>
</div>

我将在稍后阶段为文本添加媒体查询断点。

https://jsfiddle.net/vkchxz3q/

3 个答案:

答案 0 :(得分:0)

我假设您正在尝试将文本中心垂直放置在固定高度。为此,您可以使用表格属性进行垂直对齐,浏览器支持 - &gt; http://caniuse.com/#search=css-table

#fader {
    display: table;
}
.table-cell {
    display: table-cell;
    vertical-align: middle;
}

实施例: https://jsfiddle.net/vkchxz3q/31/

要使高度动态,只需取消#fader的高度 https://jsfiddle.net/vkchxz3q/33/

答案 1 :(得分:0)

我会移除position:absolute;,然后计算出容器的高度,以及在你的间隔中应用绝对定位。

https://jsfiddle.net/vkchxz3q/35/

&#13;
&#13;
var s, q, l;

s = $('#fader');
q = s.children('blockquote');
l = q.length;

var i = 0;
setInterval(function() {
  q.eq(i).removeClass('active');
  i == l - 1 ? i = 0 : i++;
  q.eq(i).addClass('active').css('position', 'absolute');
}, 10000);

var intHeight = 0;
q.each(function() {
  if ($(this).outerHeight() > intHeight) {
    intHeight = $(this).outerHeight();
  }
});
$('#quote-container').height(intHeight);
&#13;
* {
  box-sizing: border-box;
}
#quote-container {
  width: 100%;
  padding: 40px;
  height: 300px;
  /* Definative Height */
  background: #353535;
}
#fader {
  display: block;
  position: relative;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}
blockquote {
  visibility: hidden;
  top: 0;
  left: 0;
  font-family: Helvetica, sans-serif;
  font-size: 2em;
  color: #fff;
  text-align: center;
  opacity: 0;
  margin: 0;
}
blockquote span {
  display: block;
  font-size: .6em;
  font-style: italic;
  margin-top: 10px;
}
.active {
  visibility: visible;
  opacity: 1;
  -webkit-transition: opacity 1.5s ease-in;
  transition: opacity 1.5s ease-in;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quote-container">
  <div id="fader">
    <blockquote class="active">Sometimes it is better to just walk away from things and go back to them later when you’re in a better frame of mind. <span>- Joe Blogs, Blogs Incorperated</span>

    </blockquote>
    <blockquote>If you like tuna and tomato sauce- try combining the two. It’s really not as bad as it sounds. <span>- John Smith, Kansas Kyak Club</span>

    </blockquote>
    <blockquote>Last Friday in three week’s time I saw a spotted striped blue worm shake hands with a legless lizard. <span>- Jon Doe , Riverford Farm</span>

    </blockquote>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

当所有元素不是.active并且浮动到一侧而不是使用绝对定位时,使所有元素都具有很大的负值#quote-container。然后给他们的容器overflow: auto;go.tag以使其考虑浮动元素&#39;高度。

https://jsfiddle.net/vkchxz3q/36/