简体   繁体   中英

Set div 50% height of parent div

I want the child div to be a 50% height of the parent, so if the parent div was 100%, the child div would be 50%, if the parent div was 1000px, the child div would still be 50%.

Here's a basic fiddle of what i've done so far http://jsfiddle.net/6PA6k/17/

Here's the html

<div class="wrapper">
  <div class="button-container">
    <div class="button"></div
  </div>
</div>

Here's the 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;
}

UPDATED

Demo: 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;
}

I may be confused about what you are asking, but changing:

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

To:

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

Does what you seem to want... http://jsfiddle.net/c3eB8/

EDIT

Ok, so now that I understand the question better, in order to center the child div vertically with a parent div without fixed dimensions, you can use absolute positioning.

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

Here is a fiddle: http://jsfiddle.net/8UjvB/

Maybe this: http://jsfiddle.net/helderdarocha/8p5MT/

It places the 50x50 button in the middle of the parent:

.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;
}

(add position:relative to the parent, and margin:auto; position:absolute; top:0; bottom:0 to the .button statement)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM