I want two elements to take up an exact percent of the parent\'s width, but I also need margins on them holding them apart. I have the following markup:
calc()
Using CSS3's calc() length, you can do this by setting the width of the .element
to:
.element {
width: 49%; /* poor approximation for old browsers */
width: calc(50% - 8px); /* standards-based answer for IE9+, FF16+ */
width: -moz-calc(50% - 8px); /* support for FF4 - FF15 */
width: -webkit-calc(50% - 8px); /* support for Chrome19+ and Safari6+ */
}
See http://caniuse.com/calc for details on which browsers and versions support this.
Calculations can be made by piling up multiple elements. For this case, we wrap each 'element' in a wrapper that is 50% wide but with a 4px padding:
HELLO
WORLD
.ele1 {
display:inline-block;
width:50%;
padding:4px;
box-sizing:border-box; /* Make sure that 50% includes the padding */
-moz-box-sizing:border-box; /* For Firefox */
-webkit-box-sizing:border-box; /* For old mobile Safari */
}
.element {
background:#009; color:#cef; text-align:center;
display:block;
}
The same result can be made by treating the wrapper as a 'table' and each element as a cell within the same row. With this, whitespace between elements is not important:
HELLO
WORLD
.wrap {
background:red;
width:300px;
display:table;
border-spacing:4px
}
.element {
background:#009; color:#cef; text-align:center;
width:50%;
display:table-cell;
}
Note that this last technique collapses the 4px spacing between the two elements, while the first two techniques cause 8px to appear between the two items and 4px at the edges.