Parent div Not getting height if child div is absolute

主宰稳场 提交于 2019-12-26 10:43:31

问题


I just stuck in position, I used position:relative for parent and position:absolute for child now parent div did't get height and i don't want to use min-height or height. You can see the red border on top which is the parent div border.

fiddle code

.box {
  text-align: center;
  border: 1px solid red;
  width: 500px;
  margin: 0 auto;
  position: relative;
}

.content {
  width: 50%;
  position: absolute;
  left: 0;
  right: 0;
  margin: 0 auto;
}
<div class="box">
  <div class="content">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda adipisci vel, dolore aspernatur iste iure blanditiis quam esse repudiandae aperiam debitis doloribus necessitatibus placeat tempora voluptate totam exercitationem neque quae.
  </div>
</div>

Help me please ?

Thanks


回答1:


You could just make the outer box absolute, if your textbos has to be positioned absolute.

EDIT: Without being able to edit the HTML structure, you need specific heights or some JavaScript. More Information about position

.box {
  text-align: center;
  border: 1px solid red;
  width: 500px;
  margin: 0 auto;
  position: absolute;
}

.content {
  width: 50%;
  left: 0;
  right: 0;
  margin: 0 auto;
}
<div class="box">
  <div class="content">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda adipisci vel, dolore aspernatur iste iure blanditiis quam esse repudiandae aperiam debitis doloribus necessitatibus placeat tempora voluptate totam exercitationem neque quae.
  </div>
</div>



回答2:


Its not possible without javascript but you can get this if add a child element inside the '.content'...

.box {
  text-align: center;
  
  width: 500px;
  margin: 0 auto;
  position:relative;
}

.content {
  border: 1px solid red;
  width: 100%;
  position:absolute;
  left:0;
  right:0;
}
.inner{
  margin: 0 auto;
  width: 50%;
}
<div class="box">
  <div class="content">
  <div class="inner">   
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda adipisci vel, dolore aspernatur iste iure blanditiis quam esse repudiandae aperiam debitis doloribus necessitatibus placeat tempora voluptate totam exercitationem neque quae.
    </div>
  </div>
</div>



回答3:


Absolute positioning takes an element out of normal flow, so it can not change the measures of its parent any more. Try this, it works fine:

.box {
    text-align: center;
    border: 1px solid red;
    width: 500px;
    height:100%;
    margin: 0 auto;
}

.content {
    width: 50%;
    margin: 0 auto;
}


来源:https://stackoverflow.com/questions/45008621/parent-div-not-getting-height-if-child-div-is-absolute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!