父div中的div

时间:2014-11-11 17:27:20

标签: html css center

我试图根据父div的维度将div放在父div中。我尝试过使用:

display: inline-block;

因为我已经看到其他问题,这被用来居中div,但我没有运气。

BOX1应该以测试为中心

<div class="tab-pane" id = "test">
    <div id="Box2"> 
        <h1> Graph Text </h1>
  </div>
    <div id="BOX1">
  </div>
</div>


#test {
    width:700px;
    height: 500px;
    background: grey;
    position:relative;
}

#BOX1 {
    display: inline-block;
    width: 500px;
    height: 300px;
    background: lightgrey;  
    position:absolute;
    z-index:1;
}

#Box2{
    width: 250px;
    height: 50px;
    background: lightblue;
    position:absolute;
    left: 125px;
    z-index:2;
}

h1 {
  font: 25px Helvetica, sans-serif;
  text-align: center;
}

http://jsfiddle.net/bahanson/xvL2qvx0/5/

5 个答案:

答案 0 :(得分:1)

试试这个:demo

#test {
    width:700px;
    height: 500px;
    background: grey;
    position:relative;
}

#BOX1 {
	margin:0 auto;
    width: 500px;
	height: 300px;
	background: lightgrey;	
	position:relative;
    z-index:1;
}

#Box2{
  	width: 250px;
    height: 50px;
    background: lightblue;
    position:absolute;
    left: 125px;
    z-index:2;
}

h1 {
  font: 25px Helvetica, sans-serif;
  text-align: center;
}
<div id="test" class="tab-pane">
    
    <div id="BOX1">
  <div id="Box2"> 
        <h1> Graph Text </h1>
  </div>
  </div>
</div>

答案 1 :(得分:0)

将此添加到方框1 css可以执行您想要的操作,并且如果父宽度发生更改,则会使子项居中。

left: 50%;
margin-left: -250px;

http://jsfiddle.net/xvL2qvx0/6/

如果您不需要IE8支持,可以使用:

left: calc(50% - 250px);

答案 2 :(得分:0)

您应该阅读正常流程和CSS定位。

http://webdesign.about.com/od/cssglossary/g/bldefnormalflow.htm

但基本上,div总是相对于父div而言。

如果您将margin: 0 auto;添加到div,则应将其水平放置在父div

答案 3 :(得分:0)

#BOX1 {
    display: inline-block;
    margin-left:100px;
    width: 500px;
    height: 300px;
    background: lightgrey;  
    position:absolute;
    z-index:1;
}

使用margin-left命令将其调整到中心....

答案 4 :(得分:0)

如果你使用绝对定位,你可以简单地给它toprightleftbottom 0并使用{{ 1}}水平和垂直居中。

如果您希望不涉及数学,则可以使用相对(百分比)大小调整。此外,如果您稍后更改尺寸(可能通过移动设备的媒体查询),则无需重新计算杂乱的边距或偏移 - 只需更改尺寸即可居中。

margin:auto

http://jsfiddle.net/xvL2qvx0/7/

#BOX1 {
    display: block;
    width: 500px; /* it will still work if you change the size */
    height: 300px; /* the dimensions could be percentages if you like */
    background: lightgrey;  
    position:absolute;
    z-index:1;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
}
#test {
    width:700px;
    height: 500px;
    background: grey;
    position:relative;
}

#BOX1 {
    width: 500px;
	height: 300px;
	background: lightgrey;	
	position:absolute;
    z-index:1;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
}

#Box2{
  	width: 250px;
    height: 50px;
    background: lightblue;
    position:absolute;
    left: 125px;
    z-index:2;
}

h1 {
  font: 25px Helvetica, sans-serif;
  text-align: center;
}