【问题标题】:html show parent div on center of child div having height greater than childhtml在子div的中心显示父div,其高度大于子div
【发布时间】:2017-02-10 07:29:14
【问题描述】:

我有一个像这样的 div:

<div style="background-color: blue; height: 10px">
    <div style="height: 20px; width: 10px">
    </div>
</div>

这里我有一个 div,其中包含一个高度是其父 div 的两倍的 div。

子元素的高度是其父元素的两倍,但其额外的 10px 高度显示在底部。

如果父 div 是 10 像素,子 div 是 20 像素,我想要什么,子 div 应该在底部和顶部平均显示额外的 10 像素,就像父 div 居中一样。

这样做的正确方法是什么?

【问题讨论】:

  • 'position' 是你的朋友。

标签: html css


【解决方案1】:

您可以使用绝对位置,然后减去父级高度的一半:

<div style="background-color: blue; height: 100px; width:100px">
    <div style="height: 200px; width: 100px; background-color: green; opacity: 0.5; position: absolute; top:-50px">
    </div>
</div>

在此处查看代码笔:http://codepen.io/fennefoss/pen/qRQdyP

【讨论】:

    【解决方案2】:

    下面发布的没有绝对定位的代码也可以。

    .parent {
    	background-color: blue; 
    	height: 10px;
    }
    
    .child {
    	height: 20px;
    	width: 50px;
    	background-color: red;
    	position: relative;
    	top: 50%;
    	transform: translateY(-50%);
    }
    <div class="parent">
        <div class="child"></div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 2013-06-25
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多