margin CSS property, but it doesn't exist. How could I fake it?
I am trying to make a simple page with the following characteristics:
Transforming these requirements into a linear programming problem, we get:
DEFINITIONS:
BRWS = (width of the browser window, not a variable)
BODY = (width of the document's body)
LRMG = (width of the document's left and right margins)
HSCR = (range of the browser window's horizontal scroll bar)
OBJECTIVE:
MIN HSCR /* Third requirement */
CONSTRAINTS:
HSCR = BODY + 2*LRMG - BRWS /* From the definition of how a browser's
* horizontal scrollbar works. */
BODY >= 60 /* First requirement */
LRMG <= 3 /* Second requirement */
LRMG >= 0 /* Physical constraint, margins cannot be negative */
HSCR >= 0 /* Physical constraint, scroll bars cannot have negative ranges */
Solving this linear program, we get:
BODY = (BRWS <= 66) ? 60 : (BRWS - 6)
HSCR = (BRWS >= 60) ? 0 : (60 - BRWS)
LRMG = (BRWS + HSCR - BODY) / 2
(Sorry for the boring math, but I am not confident that the original explanation in English was clear enough.)
Now back to the actual page. After googling to find what I could do with CSS, I managed to implement the first two requirements using the following code:
body {
min-width: 60em; /* First requirement */
}
/* The document's body has only two children, both of which are divs. */
body > div {
margin: 0 3em; /* Second requirement, but in a way that makes */
max-width: 100%; /* it impossible to satisfy the third one. */
}
If CSS had a max-margin
property, satisfying all requirements would be easy:
body > div {
max-margin: 0 3em;
max-width: 100%;
}
But, of course, max-margin
does not exist. How could I fake it?
Spacer divs on either side of the content divs. Those are your margins. Set their max width using the max-width property.
模仿可变宽度左边距:
.div-class {
display: inline-block;
}
.div-class:before {
content: '';
width: 10%;
min-width: 100px;
max-width: 200px;
display: inline-block;
}
For pure CSS that works in any scenario:
You'll just need to do the math to figure out the static sizes at the break point to make sure it scales fluidly.
Sample Code:
.my_class {
margin: 0px 10%;
}
@media screen and (min-width: 480px) {
.my_class {
margin: 0px 10px;
}
}
This will make .my_class
follow both:
margin: 0px 10%;
at over a screen width of 480px margin: 0px 10px;
at under 480px. 上一篇: 使用填充百分比来定位边框大小的问题