What happen if a client wants a pixel perfect design, or in this case "percent perfect" like this example?
The full container is 100% height, so the sum of all divs and spaces results in 100% height.
The problem here is that i tried to add the spaces using margin-bottom in divs but realized that the percent margins don't represent the desired value inside the full container of 100% height.
The only solution that I know is using divs with % height instead of margins. But i want to do a cleaner html. Is there another alternative for this?
Additional info: I am using phonegap + ionic, is a mobile design.
First you will have to set the root element to height:100vh
Then use :nth-child
to set the height and the margin of each divs
*{box-sizing: border-box}
:root{width: 100vw; height: 100vh; text-align: center}
body{padding: 0; margin:0}
div{
display: block;
background: #333;
width: 480px;
}
div:first-child, div:nth-child(2){
height: 15vh;
margin: 0 0 2.5vh 0
}
div:nth-child(3){
height: 20vh;
margin: 0 0 5vh 0
}
div:nth-child(4){
height: 30vh
}
<div></div>
<div></div>
<div></div>
<div></div>
I was recommended to post my fiddle as an answer. So here is the rundown: The issue that OP is running into is that margin is calculated as a percent of the width (See "<percentage>") when you use percents. That means that margin-bottom: 50%
is 50% of the width of the container, not the height. One way around this is to use vh
(viewport height) unit of measure. This is of course limited to a percent of the viewport and not a container, but as long as your design is essentially full screen with no scrolling, it's a possible solution (credit to the user @Tambo for coming up with it first).
Compatibility is also a concern (esspecially for IE): http://caniuse.com/#feat=viewport-units
Here is the important part of the solution
.small {
height: 15%;
margin-bottom:2.5vh;
}
.medium {
height: 20%;
margin-bottom:5vh;
}
.large {
height: 30%;
margin-bottom:10vh;
}
And the demo link: http://jsfiddle.net/c28h58cw/
Why don't you just use common sense arithmetic and absolute positioning? You won't need to check browser support that way.
div {
background-color: #888;
position: absolute;
left: 0;
width: 100%;
}
div:nth-child(1) {
top: 0;
height: 15%;
}
div:nth-child(2) {
top: 17.5%;
height: 15%;
}
div:nth-child(3) {
top: 35%;
height: 20%;
}
div:nth-child(4) {
top: 60%;
height: 30%;
}
<div></div>
<div></div>
<div></div>
<div></div>
Note that percentage top and bottom margins are relative to parent element's width, not height. Just another CSS WTF.
you could use
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
which makes the height and width include any padding/borders, have a look http://css-tricks.com/box-sizing/