2016-11-11 50 views
1

基本上我试图将一个图标放在内部div的中心。在我的代码中,div里面有一个div。我想在最里面的div中居中文,所以我尝试使用margin-top:50%相反,文本走得更远。我认为最内层的div会在父分区和相应的位置找到中间点。请解释我为什么错了。 thx保证金顶部百分比与父div不匹配

<html> 
<body> 
<div id="container" style="height:1000px;width:100%;background-color: green;position:absolute;"> 

    <div id="inner" style="height:50%; width:50%; background-color: black;margin-top:50%;display:inline-block;"> 
     <div id="inner" style="height:50%; width:50%; background-color: yellow"></div> 
    </div> 
</div> 
</body> 
+0

我试图使HTML 100%高,但仍申报单没有很好地排队。这里是js小提琴:https://jsfiddle.net/op8sdq0a/ – st4rgut

+0

感谢球员,我正在使用上面的例子作为这个网站的简化我正在尝试做,我想让箭头在照片中间画廊(绿色div)在任何一方。对不起,如果前面的例子提出了一个不同于这个小提琴的问题:https://jsfiddle.net/fqLmcnL3/1/ – st4rgut

回答

2

margin-top:50%意味着该元件的上边框将在垂直半,它不居中元件。

要居中该元素,最好使用相对位置和display:block所有元素,top:50%left: 50% HICH左上角移到父的中心,另外transform:translate(-50%, -50%),其移回(上和左)由其自身高度和宽度的一半。

此外,父元素必须有一个定义的高度(在你的情况是真的)。下面是完整的代码小提琴:

https://jsfiddle.net/49Lvzszj/1/

+0

即时好奇,为什么你使用内部divs相对postioning而不是绝对定位 – st4rgut

+0

绝对位置将作为在这种情况下,但我更喜欢使用相对的方式,因为它不会将元素从父元素的上下文中取出,这对于元素的内容可以是动态元素以及何时存在多个子元素是有利的。顺便说一句:我注意到在你的小提琴中有两个ID为“inner”的元素 - 不应该这样做 - 使这些类代替ID(一个ID在页面中应该是唯一的)。 – Johannes

2

Fiddle

 * { 
 
      box-sizing: border-box; 
 
     } 
 
     .first { 
 
      height: 500px; 
 
      background-color: black; 
 
      display: table-cell; 
 
      width: 500px; 
 
      text-align: center; 
 
      vertical-align: middle; 
 
     } 
 
     
 
     .second { 
 
      display: flex; 
 
      justify-content: center; 
 
      height: 300px; 
 
      width: 300px; 
 
      background-color: white; 
 
      margin: 0 auto; 
 
     } 
 
     
 
     .third { 
 
      align-self: center; 
 
      height: 200px; 
 
      width: 200px; 
 
      background-color: green; 
 
      padding: 25%; 
 
     }
<div class='first'> 
 
    <div class='second'> 
 
    <div class='third'>Text is hereby centered!</div> 
 
    </div> 
 
</div>

相关问题