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?
You cannot see the effect of margin-right because the 'width' property of div causes the margin of div to have more than 10px distance from the right wall of the body. Consequently, it causes the margin-right property not to have any visual effect.
In 2020 this is now very straightforward using the CSS math functions: min(), max(), and clamp(). A min calculation picks the smallest from a comma separated list of values (of any length). This can be used to define a max-padding or max-margin rule: padding-right: min(50px, 5%);
Spacer divs on either side of the content divs. Those are your margins. Set their max width using the max-width property.
To mimic a variable-width left margin:
.div-class { display: inline-block; } .div-class:before { content: ''; width: 10%; min-width: 100px; max-width: 200px; display: inline-block; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With