将 div 的高度设置为父 div 的 50%

8
我希望子div的高度是父元素的50%,所以如果父div是100%,子div将是50%,如果父div是1000像素,子div仍然是50%。
以下是我已经完成的基本fiddle:http://jsfiddle.net/6PA6k/17/ 以下是html:
<div class="wrapper">
  <div class="button-container">
    <div class="button"></div
  </div>
</div>

这里是CSS。
* {
  margin:0;
  padding:0;
}
html {
  height:100%;
  width:100%;
}
body {
  height:100%;
  width:100%;
}
.wrapper {
  height:100%;
  width:100%;
  background:red;
}
.button-container {
  height:100%;
  width:50px;
}
.button {
  width:50px;
  height:50px;
  background:blue;
}

1
我不明白你所说的“parent”和“child”。顺便说一下,将height: 100%或其他设置为“parent”,将height: 50%;设置为“child”。 - Hashem Qolami
似乎您将“px”和“%”混淆了。 - helderdarocha
3个回答

6

更新

示例: http://jsfiddle.net/6PA6k/22/

* {
    margin:0;
    padding:0;
}
html {
    height:100%;
    width:100%;
}
body {
    height:100%;
    width:100%;
}
.wrapper {
    position: relative;
    height:80%;
    width:100%;
    background:red;
}
.button-container {
    position: relative;
    height:50%;
    width:300px;
    background:blue;
}
.button {
    position: absolute;
    top: 50%;
    height:50px;
    width:50px;
    background:yellow;
    margin-top: -25px;
}

不太对,也许我没有正确解释。我想要一个按钮,大小为50px x 50px,高度为父div的50%。 - user1221565
一个大小为50px x 50px的按钮需要浮动在容器的50%高度处,例如一个红色背景,中间有一个50px x 50px的正方形(高度)。 - user1221565

2

我可能对你的问题有些困惑,但是将以下内容更改:

.button {
  width:50px;
  height:50px;
  background:blue;
}

致:

.button {
  width:50px;
  height:50%;
  background:blue;
}

我想你想要的是什么... http://jsfiddle.net/c3eB8/

编辑

好的,现在我更好地理解了这个问题。为了在没有固定尺寸的父 div 中垂直居中子 div,您可以使用绝对定位。

.button {
    width:50px;
    height:50px;
    background:blue;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}

这里有一个 jsfiddle: http://jsfiddle.net/8UjvB/


不太对,也许我没有正确地解释自己。我想要一个按钮,大小为50px x 50px,高度为父div的50%。 - user1221565
你的意思是想要一个50x50像素的按钮浮动在一个占父级div 50%的div中间? - helderdarocha
@user1221565 我不太明白,你想要按钮位于父级div的中心(50%),还是你希望它是父级div大小的一半(50%)? - Dryden Long
基本上我想要一个50像素 x 50像素的 div,它浮动在父 div 的中间(高度)。 - user1221565

0

或许这个可以:http://jsfiddle.net/helderdarocha/8p5MT/

它将50x50的按钮放置在父元素的中心:

.button-container {
    height:100%;
    width:50px;
    background: green;
    position: relative;
}
.button {
    width:50px;
    height:50px;
    background:blue;
    margin: auto;
    position: absolute;
    top: 0; bottom: 0;
}

(在父级元素中添加position:relative,并在.button语句中添加margin:auto; position:absolute; top:0; bottom:0


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接