」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 無需媒體查詢的響應式佈局

無需媒體查詢的響應式佈局

發佈於2024-11-08
瀏覽:149

How often do you use media queries when building web layouts? I’ve spent too much time on them!

First you spent quite a lot of time trying to make the layout exactly like in the design. But then you need to resize your browser to all possible screen resolutions to make sure your page still looks good on all of them. And I mean to resize not only by width, but by height too - especially, if you have full height sections.

Eventually, your CSS become full of lines like these:

@media screen and (max-width: 1199px) { /*styles here*/ }
@media screen and (max-width: 1023px) { /*more styles here*/ }
@media screen and (max-width: 767px) { /*another styles here*/ }

And that’s annoying! Won’t it be much easier if you can include responsiveness kind of like automatically? Of course, you still need to provide the rules for the responsiveness, but without need to write them for dozens of screen resolutions.

Units system

The first thing you need to understand about responsive design is that you have to forget about pixels.

I know it might be hard to switch from one unit to another, but using pixels is the voice from the past.

The biggest problem with using pixels as a size unit is that you don’t get in count the user's device from which it views your website.

The default root font size for modern browsers is 16px. That means 1rem = 16px. But that doesn't mean users cannot change that value in browser settings to whatever they want.

So imagine the user's default browser font size is 24px. But you setted up the font size of the body tag to 16px.

Here’s what user expects to see:

Responsive Layouts Without Media Queries
Root font size equals 24px

And this is what user actually sees:

Responsive Layouts Without Media Queries
Root font size equals 16px

It especially affects people with vision problems, thus your page won’t be very accessible for them.

Of course, they can always zoom your page, but in this case it will affect other opened websites, which may not be supposed to be zoomed in.

BTW, the Lorem Ipsum site is a very “good” bad example of how non UX-friendly a page can look if you’re using pixels for fonts, margins, paddings etc.

If you're not familiar with the relative units like rem and vw, you should check this article on the MDN, where you can deep dive into CSS units and values: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units

Setup variables

To make it easier to build the layout, let's set up global variables first. Luckily, in CSS we have that opportunity. Since custom variables are subject to the cascade and inherit their value from their parent, we will define them on the :root pseudo-class, thus they can be applied to the whole HTML document.

:root {
  --primary-color: green;
  --primary-font: Helvetica, sans-serif;
  --text-font-size: clamp(1rem, 2.08vw, 1.5rem);
}

Looks pretty simple - we define a variable name, which must begin with a double hyphen (--). Then provide a variable value, which can be any valid CSS value.

Then we can use those variables for any element or even pseudo-class in the document using the var() function:

color: var(--primary-color);

For example, we can use our --primary-color variable for all the headings on the page like this:

h1, h2, h3, h4, h5, h6 {
  color: var(--primary-color);
}

Since the primary colour will use quite a lot of different elements on the page, it’s very handy to use the variable instead of writing each time the colour itself.

The last variable --text-font-size: clamp(1rem, 2.08vw, 1.5rem) might look odd: what’s the clamp and what’s it doing on the font size variable?

Dynamic font scaling

The clamp() CSS function clamps a middle value within a range of values between a defined minimum bound and a maximum bound.

You need to provide a minimum value (which is 1rem from the example above), a preferred value (2.08vw) and the maximum allowed value (1.5rem).

The most tricky part here is to set the preferred value. It should be in some viewport relative units (like vw or vh). Thus when a user resizes its browser or changes the device’s orientation the font size will scale proportionally.

I’ve made this formula for calculating the preferred value:

value = AMValue * remInPx / (containerWidth / 100)

Here comes an explanation, no panic:

AMValue - arithmetic mean, between the minimum and maximum allowed values in rem. In our example it equals (1rem 1.5rem) / 2 = 1.25rem

remInPx - default size of 1rem in pixels, depending on your design, usually it equals to 16px

containerWidth - the maximum width of your content container block (in pixels). We need to divide that value to 100 to get the 1% of the width. In the example it equals 960px.

So if you replace the arguments in that equation with real numbers you will get:

value = 1.25 \* 16 / (960 / 100) = 2.08

Let’s check how it will scale:

I know it’s not a perfect solution. Besides, we attach again to pixels, when calculating the preferred value. It’s just one of many possible options to make our fonts scale between viewports sizes.

You can use other CSS functions like min() or max(), or create a custom method to calculate the preferred value in the clamp() function.

I wrote an article about dynamic font size scaling, only for pixel units. It’s a bit outdated, but still you might find it helpful:

Dynamic font-size using only CSS3

Ok, enough of the fonts, let’s go further to the layout!

Layout with equal column width

Let’s start with some simple layout with 6 equal columns.

With media queries you need to write a bunch of extra CSS code to handle how they should wrap on different screen sizes. Like this:

/* by default we have 6 columns */
.column {
  float: left;
  width: calc(100% / 6);
}
/* decrease to 4 columns on the 1200px breakpoint */
@media screen and (max-width: 1200px) {
  .column {
    width: calc(100% / 4);
  }
}
/* decrease to 3 columns on the 1024px breakpoint */
@media screen and (max-width: 1024px) {
  .column {
    width: calc(100% / 3);
  }
}
/* finally, decrease to 2 columns for the viewport width less than or equal to 768px */
@media screen and (max-width: 768px) {
  .column {
    width: calc(100% / 2);
  }
}

Woah! That’s a lot of code, I must say! Wouldn't it be better to just make it scale automatically?

And here’s how, thanks to the CSS grid layout:

.row {
  display: grid;
  grid-template-columns: repeat( auto-fit, minmax(10em, 1fr) );
}

All we need to do is to set the parent block of our columns to be displayed as a grid. And then, create a template for our columns, using grid-template-columns property.

This is called RAM technique (stands for Repeat, Auto, Minmax) in CSS, you can read about it in more details here:

RAM Technique in CSS

In that property we use the CSS repeat() function.

The first argument is set to auto-fit, which means it FITS the CURRENTLY AVAILABLE columns into the space by expanding them so that they take up any available space. There’s another value for that argument: auto-fill. To understand the difference between them check this pen:

Also, I highly recommend to read this article from CSS tricks about auto sizing columns in CSS grid: https://css-tricks.com/auto-sizing-columns-css-grid-auto-fill-vs-auto-fit/

The second argument is using another function minmax(), which defines the size of each column. In our example each column should not be less than 10em and should be stretched to the remaining space.

Looks fine, but we have a problem - the number of columns can be bigger than 6!

To make a limit of columns, we need some custom formula again. But hey, it’s still in CSS! And it’s not that scary, basically, you just need to provide a gap for the grid, a minimal column width and the max number of columns.

Here’ the code:

.grid-container {

  /** * User input values. */
  --grid-layout-gap: 1em;
  --grid-column-count: 4;
  --grid-item--min-width: 15em;

  /** * Calculated values. */
  --gap-count: calc(var(--grid-column-count) - 1);
  --total-gap-width: calc(var(--gap-count) * var(--grid-layout-gap));
  --grid-item--max-width: calc((100% - var(--total-gap-width)) / var(--grid-column-count));

  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(max(var(--grid-item--min-width), var(--grid-item--max-width)), 1fr));
  grid-gap: var(--grid-layout-gap);

}

And here’s what we achieve with that:

As you can see, we can use the relative values for the columns min width and gap, which makes this code like the perfect solution. Until they build the native CSS property for that, of course ?

Important notice! If you don't need a gap between columns, you need to set it to 0px or 0em, not just 0 (pure number). I mean you have to provide the units, otherwise the code won’t work.

I’ve found that solution on CSS tricks, so in case you want to dive deeper to how that formula works, here’s the original article about it: https://css-tricks.com/an-auto-filling-css-grid-with-max-columns/

Layout with different column width

The solution above works perfectly for the grids with equal width of the columns. But how to handle layouts with unequal columns? The most common example is a content area with a sidebar, so let’s work with this one.

Here’s a simple markup of the content area along with sidebar:

This is content

Grid Item 1
Grid Item 2
Grid Item 3
Grid Item 4

For the .content section let’s use the flex box layout:

.content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 1rem;
}

The flex-wrap property here is important and should be set as wrap in order to force the columns (sidebar and content area) stack under each other.

For the sidebar and content columns we need to set flex properties like grow and basis:

/* Sidebar */
.content > aside {
  border: 1px solid var( - primary-color);
  padding: var( - primary-padding);
  flex-grow: 1;
  flex-basis: 15em;
}

/* Content */
.content > article {
  border: 1px solid var( - primary-color);
  padding: var( - primary-padding);
  flex-grow: 3;
  flex-basis: 25em;
}

The flex-basis property sets the initial size of the flex item. Basically, it’s a minimum width which the flex item should have.

The flex-grow property sets the flex grow factor — similar to the proportion of the flex item compared to the other flex items. It’s a very rough and approximate explanation, to understand better the flex-grow property I highly recommend to read this article from CSS tricks: https://css-tricks.com/flex-grow-is-weird/

So if we set the flex-grow: 1 for the sidebar and flex-grow: 3 for the content area, that means the content area will take approximately three times more space than the sidebar.

I also added the grid section from the previous example to demonstrate that it works inside the flex layout as well.

Here’s what we have in the final result:

Stackable columns

It’s pretty common, when you have a grid layout where text comes next to image on one row and then in reverse order on the next row:

Responsive Layouts Without Media Queries

But when the columns become stacked you want them to be in a specific order, where text comes always before image, but they don’t:

Responsive Layouts Without Media Queries

To achieve that we need to detect somehow when the columns become stacked.

Unfortunately, it’s impossible (yet) to do that with pure CSS. So we need to add some JS code to detect that:

/**
* Detect when elements become wrapped
*
* @param {NodeList} items - list of elements to check
* @returns {array} Array of items that were wrapped
*/
const detectWrap = (items) => {
  let wrappedItems = [];
  let prevItem = {};
  let currItem = {};

  for (let i = 0; i  {
  const items = wrapper.querySelectorAll(":scope > *");

  // remove ".wrapped" classes to detect which items was actually wrapped
  cover.classList.remove("wrapped");

  // only after that detect wrap items
  let wrappedItems = detectWrap(items); // get wrapped items

  // if there are any elements that were wrapped - add a special class to menu
  if (wrappedItems.length > 0) {
    cover.classList.add("wrapped");
  }

};

The function addWrapClasses() accepts two arguments.

The first one is wrapper — it’s a parent element of the items which we should check whether they are wrapped (stacked) or not.

The second argument cover is an element to which we apply a special CSS class .wrapped. Using this class you can change your layout when the columns become stacked.

If you want to apply the .wrapped class directly to the wrapper element you can pass the same element as the second argument.

For better understanding my “wonderful” explanation please see the pen below, hope it will become more clear for you:

You can also use it to detect when the header menu should be collapsed into the burger. You can read about that case in my article here:

An Easy Way to Make an Auto Responsive Menu

Combining all together

Here’s a pen with all the techniques I mentioned in this article combined:

Final thoughts

I’ve used the techniques from this article in my recent project and it worked very well. The web pages look fine on every screen with no need to optimise them manually on multiple breakpoints.

Of course I will be lying if I tell you I didn’t use media queries at all. It all depends on the design and how flexible you can be with modifying page layout. Sometimes it’s much faster and simpler just to add a couple of breakpoints and then fix CSS for them. But I think eventually CSS media queries will be replaced by CSS functions like clamp() which allow developers to create responsive layouts automatically.


If you find this article helpful — don’t hesitate to like, subscribe and leave your thoughts in the comments ?


Read more posts on my Medium blog


Thanks for reading!

Stay safe and peace to you!

版本聲明 本文轉載於:https://dev.to/bogdanfromkyiv/responsive-layouts-without-media-queries-1e73?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-12-26
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-12-26
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段中:action=''而非:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST陣列:表單提交後使用 var_dump 檢查 $_POST 陣列的內...
    程式設計 發佈於2024-12-26
  • 插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入記錄時如何解決「一般錯誤:2006 MySQL 伺服器已消失」介紹:將資料插入MySQL 資料庫有時會導致錯誤「一般錯誤:2006 MySQL 伺服器已消失」。當與伺服器的連線遺失時會出現此錯誤,通常是由於 MySQL 配置中的兩個變數之一所致。 解決方案:解決此錯誤的關鍵是調整wait_tim...
    程式設計 發佈於2024-12-26
  • HTML 格式標籤
    HTML 格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2024-12-26
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSocke...
    程式設計 發佈於2024-12-26
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-12-26
  • 如何在 HTML 表格中有效地使用 Calc() 和基於百分比的欄位?
    如何在 HTML 表格中有效地使用 Calc() 和基於百分比的欄位?
    在表格中使用Calc():克服百分比困境創建具有固定寬度列和可變寬度列的表格可能具有挑戰性,尤其是在嘗試在其中使用calc() 函數。 在 HTML 中,使用 px 或 em 設定固定列寬非常簡單。但是,對於可變寬度列,通常使用百分比 (%) 單位。然而,當在表中使用 calc() 時,百分比似乎無...
    程式設計 發佈於2024-12-26
  • 如何在PHP中透過POST提交和處理多維數組?
    如何在PHP中透過POST提交和處理多維數組?
    在PHP 中透過POST 提交多維數組當使用具有可變長度的多列和行的PHP 表單時,有必要進行轉換輸入到多維數組中。這是解決這項挑戰的方法。 首先,為每列分配唯一的名稱,例如:<input name="topdiameter[' current ']" type="...
    程式設計 發佈於2024-12-26
  • for(;;) 迴圈到底是什麼、它是如何運作的?
    for(;;) 迴圈到底是什麼、它是如何運作的?
    揭秘神秘的for(;;) 循環在古老的程式碼庫深處,你偶然發現了一個令人困惑的奇特for 循環你的理解。其顯示如下:for (;;) { //Some stuff }您深入研究線上資源,但發現自己陷入沉默。讓我們來剖析這個神秘的構造。 for 迴圈的結構Java 中的for 迴圈遵循特定的語...
    程式設計 發佈於2024-12-25
  • Java 的 Scanner.useDelimiter() 如何使用正規表示式?
    Java 的 Scanner.useDelimiter() 如何使用正規表示式?
    Java 使用Scanner.useDelimiter 了解分隔符號Java 中使用Scanner.useDelimiter 了解分隔符號Java 中的Scanner 類別提供了useDelimiter 方法,讓您指定分隔符號(代字或模式)來分隔代字幣。然而,使用分隔符號可能會讓初學者感到困惑。讓我...
    程式設計 發佈於2024-12-25
  • 如何在 Android 中顯示動畫 GIF?
    如何在 Android 中顯示動畫 GIF?
    在Android 中顯示動畫GIF儘管最初誤解Android 不支援動畫GIF,但實際上它具有解碼和顯示動畫的能力顯示它們。這是透過利用 android.graphics.Movie 類別來實現的,儘管這方面沒有廣泛記錄。 要分解動畫 GIF 並將每個幀作為可繪製對象合併到 AnimationDra...
    程式設計 發佈於2024-12-25
  • 為什麼我在執行 phpize 時出現「找不到 config.m4」錯誤?
    為什麼我在執行 phpize 時出現「找不到 config.m4」錯誤?
    解決phpize 中的“找不到config.m4”錯誤在運行phpize 時遇到“找不到config.m4”錯誤是可能阻礙ffmpeg 等擴充安裝的常見問題。以下是解決此錯誤並讓 phpize 啟動並運行的方法。 先決條件:您已經安裝了適合您的PHP 版本的必要開發包,例如php- Debian/U...
    程式設計 發佈於2024-12-25
  • 列印時如何在每頁重複表頭?
    列印時如何在每頁重複表頭?
    在印刷模式下重複表格標題當表格在印刷過程中跨越多個頁面時,通常需要有標題行(TH元素)在每頁重複,以便於參考。 CSS 提供了一種機制來實現此目的。 解決方案:使用 THEAD 元素CSS 中的 THEAD 元素是專門為此目的而設計的。它允許您定義一組應在每個列印頁面上重複的標題行。使用方法如下:將...
    程式設計 發佈於2024-12-25
  • 為什麼 `cout` 會誤解 `uint8_t` 以及如何修復它?
    為什麼 `cout` 會誤解 `uint8_t` 以及如何修復它?
    深入分析:為什麼 uint8_t 無法正確列印您遇到了 uint8_t 變數的值無法正確列印的問題庫特。經過調查,您發現將資料類型變更為 uint16_t 可以解決該問題。此行為源自於 uint8_t 的基本性質以及 cout 處理字元資料的方式。 uint8_t 在內部儲存一個無符號 8 位元整數...
    程式設計 發佈於2024-12-25

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3