Home > Software engineering >  Responsive Design: reduce breakpoints
Responsive Design: reduce breakpoints

Time:12-25

I always wondered if we could reduce breakpoints in a responsive design.

Here is a simple example. I have a form containing text inputs. The normal way for responsiveness would be to have many breakpoints for example large laptop, laptop, tablet, large phone, small phone to have the nicest width for the text inputs. But would it be possible rather to have for the text inputs width something like:

  • If screen width > 1024 -> width: 40%
  • If screen width < 481 -> width: 80%
  • For any screen width in between, use the linear interpolation (width in between 40% to 80% depending of the screen width)

Is it possible to do so with css?

CodePudding user response:

You can use media-queries to achieve these conditions. Like this:

input{
    width: 40%;
}
@media (max-width: 1024px){
    input{
        max-width: 80%;
        min-width: 40%;
    }
}
@media (max-width: 481px){
    input{
        width: 80%;
    }
}
<input type="text" placeholder="type here">

CodePudding user response:

Convert the given percentages to actual pixel values:

  • 80% of 480px yields 384,8 => p1( 480,385)
  • 40% of 1024px yields 409,6 => p2(1024,410)

Both rounded up to an integer as part of a pixel counts as a full pixel (use the decimal values instead if so required).

Then with above points p1(x1,y1) and p2(x2,y2) use the point slope form of

Linear Equation y = mx b, which is y − y1 = m(x − x1)

  • y = required result
  • m = (y2 − y1) / (x2 − x1)
  • x = 100vw
  • b = y1 − m × x1

=> substituted: y = y1 (y2 − y1) / (x2 − x1) × (x − x1)

Final result using foremetioned points: y = 0.04595589x 362.941177

Convert to CSS: calc(0.04595589 * 100vw 362.941177px)

=> simplified calc(4.596vw 362.942px) (rounded up to three decimals precision)

Reference: MathIsFun: Point-Slope Equation of a Line

Extra: Linear Equation y=mx b can be used to calculate the value of any size property relative to the viewport size.

E.g. for my base font size I usually use CSS html { font-size: calc(0.625vmin 0.75rem) } using points p1(320,14) and p2(1280,20). This makes 1rem vary from 14px on a 320px to 20px on a 1280px viewport minimum size.

Snippet

input[type="text"] {
    /* using y=mx b with points p1(480,385) p2(1024,410) */
    /* y = 0.04595589x   362.941177 */
    width: clamp(385px, 4.596vw   362.942px, 410px); /* with clamp() */
    width: calc(4.596vw   362.942px);                /* without...   */
}
<input type="text" placeholder="text">

<p>Check with DevTools:</p>
<p>At viewport width 480px, input width must be 385px.
<br>At viewport width 1024px, input width must be 410px.</p>
<p>(Provided browser zoom factor and font size settings are set to default.)</p>

  • Related