search
HomeWeb Front-endH5 TutorialAnalysis of mobile terminal REM layout adaptation method of H5 activity page

This article mainly introduces relevant information that explains in detail the mobile REM layout adaptation method of H5 activity pages. The content is quite good. I will share it with you now and give it as a reference.

After getting the design draft, how to restore the layout?

If you only need to do non-precise responsive design, then using media queries to achieve it is OK. If it is necessary to accurately restore the design draft, this is usually achieved through zooming. Common solutions include viewport-based and rem-based scaling solutions.

1 viewport scaling solution

On the mobile side, the viewport scaling page size ratio can be used to achieve the purpose.

Simply put, all the width and height pixels are the same as the visual draft output, and then the viewport is dynamically set through the ratio of the page width to the visual draft width. Core code reference of scaling solution:

(function () {
    var docEl = document.documentElement;
    var isMobile = window.isMobile /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobi/i.test(navigator.userAgent);

    function setScale() {
        var pageScale = 1;

        if (window.top !== window) {
            return pageScale;
        }

        var width = docEl.clientWidth || 360;
        var height = docEl.clientHeight || 640;
        if (width / height >= 360 / 640) {
            // 高度优先
            pageScale = height / 640;
        } else {
            pageScale = width / 360;
        }

        var content = 'width=' + 360 + ', initial-scale=' + pageScale 
          + ', maximum-scale=' + pageScale + ', user-scalable=no';
        document.getElementById('viewport').setAttribute('content', content);
        window.pageScale = pageScale;
    }
    if (isMobile) {
        setScale();
    } else {
        docEl.className += ' pc';
    }
})()

This solution was practiced in our H5 activity page design last year.

But if you want it to be displayed on the PC, since there is no zoom concept of viewport, it can only be set with a fixed value, which is not ideal.

2 rem Layout Adaptation Solution

rem Layout adaptation solution has been mentioned a lot and is widely used in the products of major Internet companies.

Simply speaking, the method is:

  1. According to the ratio of the design draft to the width of the device, dynamically calculate and set the font-size of the HTML root tag;

  2. In css, the width, height, relative position, etc. of the design draft elements are converted into values ​​in rem units according to the same proportion;

  3. Design The fonts in the manuscript use px as the unit and are slightly adjusted through media queries.

Let’s give an example to illustrate.

2.1 Dynamically set the font-size of the html tag

The first problem is the dynamic calculation of the font-size of the html tag. This depends on how to agree on the conversion ratio. Taking ten equal parts of the page width as an example, the core code reference:

(function(WIN) {
    var  setFontSize = WIN.setFontSize = function (_width) {
        var  docEl = document.documentElement; 
        // 获取当前窗口的宽度
        var  width = _width || docEl.clientWidth; // docEl.getBoundingClientRect().width;
        // 大于 1080px 按 1080
        if (width > 1080) { 
            width = 1080;
        }
        var  rem = width / 10;
        console.log(rem);
        docEl.style.fontSize = rem + 'px';
       // 部分机型上的误差、兼容性处理
        var  actualSize = win.getComputedStyle && parseFloat(win.getComputedStyle(docEl)["font-size"]);
        if (actualSize !== rem && actualSize > 0 && Math.abs(actualSize - rem) > 1) {
            var remScaled = rem * rem / actualSize;
            docEl.style.fontSize = remScaled + 'px';
        }
    }
    var timer;
    //函数节流
    function dbcRefresh() {
        clearTimeout(timer);
        timer = setTimeout(setFontSize, 100);
    }
    //窗口更新动态改变 font-size
    WIN.addEventListener('resize', dbcRefresh, false);
    //页面显示时计算一次
    WIN.addEventListener('pageshow', function(e) {
        if (e.persisted) { 
            dbcRefresh() 
        }
    }, false);
    setFontSize();
})(window)

In addition, for the H5 activity page displayed in full screen, There are requirements for the width-to-height ratio, and adjustments should be made at this time. You can do it like this:

function adjustWarp(warpId = '#warp') {
    // if (window.isMobile) return;
    const $win = $(window);
    const height = $win.height();
    let width = $win.width();
    // 考虑导航栏情况
    if (width / height < 360 / 600) {
        return;
    }
    width = Math.ceil(height * 360 / 640);
    $(warpId).css({
        height,
        width,
        postion: &#39;relative&#39;,
        top: 0,
        left: &#39;auto&#39;,
        margin: &#39;0 auto&#39;
    });
    // 重新计算 rem
    window.setFontSize(width);
}

According to this scaling method, precise layout with proportional scaling can be achieved on almost any device.

2.2 Element size value method

The second problem is the value of the element size.

Taking the width of the design draft as 1080px as an example, we divide the width into 10 equal parts for easy conversion, then 1rem = 1080 / 10 = 108px. The conversion method is:

const px2rem = function(px, rem = 108) {
    let remVal = parseFloat(px) / rem;
    if (typeof px === "string" && px.match(/px$/)) { 
        remVal += &#39;rem&#39;;
    }

    return remVal;
}

For example, there is a picture in the design draft with a size of 460x210 and a relative page position of top: 321px; left: 70;. According to the above conversion method, the final css style of the element should be:

.img_demo {
    position: absolute;
    background-size: cover;
    background-image: url(&#39;demo.png&#39;);
    top: 2.97222rem;
    left: 0.64814rem;
    width: 4.25926rem;
    height: 1.94444rem;
}

2.3 Development method of rem layout scheme

Through the above method, the rem layout scheme is realized. But manually calculating the value of rem is obviously unrealistic.

With the less/sass preprocessing tool, we only need to set the mixins method, and then set the value according to the actual size of the design draft. Taking less as an example, the mixins reference is as follows:

// px 转 rem
.px2rem(@px, @attr: &#39;width&#39;, @rem: 108rem) {
    @{attr}: (@px / @rem);
}

.px2remTLWH(@top, @left, @width, @height, @rem: 108rem) {
    .px2rem(@top, top, @rem);
    .px2rem(@left, left, @rem);
    .px2rem(@width, width, @rem);
    .px2rem(@height, height, @rem);
}

For the example element in the previous article, the css style can be written like this:

.img_demo {
    position: absolute;
    background-size: cover;
    background-image: url(&#39;demo.png&#39;);
    .px2remTLWH(321, 70, 460, 210);
}

Here, the width and height can be read directly from the size of the picture element output by the design draft; the value of top/left can be quickly obtained by moving the reference line to position the element in Photoshop.

2.4 Use px as the unit for fonts

Using rem scaling for fonts will cause display problems. You only need to use media queries to set several sizes. .

Example reference:

// 字体响应式
@media screen and (max-width: 321px) {
    body {
        font-size: 13px;
    }
}

@media screen and (min-width: 321px) and (max-width: 400px) {
    body {
        font-size: 14px;
    }
}

@media screen and (min-width: 400px) {
    body {
        font-size: 16px;
    }
}

The above is the entire content of this article. I hope it will be helpful to everyone’s learning. Please pay attention to more related content. PHP Chinese website!

Related recommendations:

How to use WeChat’s embedded H5 web page to solve the problem of JS countdown failure

How to enable HTML5 to implement mobile copy Function

H5 horizontal and vertical screen detection method

The above is the detailed content of Analysis of mobile terminal REM layout adaptation method of H5 activity page. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools