Responsive Web Design
Basic knowledge of mobile development
1. REM Dimensional unit
Definition : REM (Root EM): a relative unit based on the font size of the root element (HTML element).
Application : In mobile development, REM is used to implement responsive layout. Maintain consistency and scalability across different devices by setting the font size of the root element and controlling the size of all elements using REM units.
2. Common units for mobile terminal development
px (pixel) : absolute unit, corresponding to the physical pixels of the device .
em : Relative unit, based on the font size of the parent element.
vw/vh (percentage of window width/height) : changes based on window size.
3. Viewport
Concept : User-visible areas on a web page. The viewport of mobile devices is smaller than the screen and requires special settings to optimize the display effect.
meta tag :
<meta name="viewport" content="width=device-width, initial-scale=1.0">
control viewport size and zoom level
4. Viewport viewport concept
Viewport width : Control the viewport width, set to the device screen width (
width=device-width
).Zoom : Control the initial and variable
initial-scale
zoom level of the web page through theminimum-scale
and attributes .maximum-scale
5. Get viewport data
Code example :
const width = window.innerWidth; // 获取视口宽度 const height = window.innerHeight; // 获取视口高度 console.log(`视口宽度: ${width}, 视口高度: ${height}`);
Application : Obtain viewport data through JS to adjust layout or implement specific functions, such as dynamically loading images or content based on the viewport size.
Commonly used layouts
1. VW + REM layout
Usage scenario : Dynamically adjust element size based on viewport width.
Method to realize :
Set the HTML root font size to:
html { font-size: 2vw; }
, which will1rem
equal 2% of the viewport width.All elements that require responsive scaling
rem
are sized using units, e.g.width: 10rem;
equal to 20% of the viewport width.
2. Fluid layout
Usage scenario : Suitable for simple responsive design, where the width of the element needs to change according to the percentage of the width of the container.
Method to realize :
Set container and element widths using percentages:
width: 100%;
.Media queries adjust layout properties for different screen sizes, such as minimum and maximum width constraints.
3. Flex flexible layout
Usage scenarios : Suitable for any scenario that requires one-dimensional layout control, such as row or column alignment and distribution.
Key attributes :
display: flex;
- Define a Flex container.flex-direction: row | column;
- Control the spindle direction.justify-content: center | space-between | flex-start;
- Alignment along the main axis.align-items: center | flex-start;
- Alignment along the cross axis.
Method to realize :
Set the container to
display: flex;
, and the child elements automatically become flex items.Use the
flex-grow
andflex-shrink
properties to control the scaling of items.
4. Grid layout
Usage scenarios : Suitable for complex two-dimensional layout requirements, such as grid systems and complex alignment patterns.
Key attributes :
display: grid;
- Define a Grid container.grid-template-columns: repeat(3, 1fr);
- Define three columns and assign one share of the container width to each column.grid-template-rows: auto;
- Line height automatically adjusts based on content.grid-gap: 10px;
- Define the spacing between rows and columns.grid-area
- Assign projects to designated areas.
Method to realize :
Set the container to
display: grid;
definegrid-template-columns
andgrid-template-rows
create the grid structure.Items are passed through
grid-column
andgrid-row
placed in specific cells or areas.
fluid layout
Fluid layout, also known as liquid layout, is a layout method that is widely used in web design and is especially suitable for building responsive websites. In a fluid layout, the width of an element is not fixed but is defined using a percentage, allowing the layout to dynamically adjust based on the screen size of the user's device. This article will explore in detail the concept, advantages, application examples, and comparison of fluid layout with other layout technologies.
Fluid Layout Concept
Fluid layout sizes containers based on percentage widths rather than fixed pixels, allowing page elements to automatically resize as the browser window scales. For example, if you set the width of an element to 50%, the element will always occupy half the width of the viewport, no matter how the screen size changes.
Advantages of fluid layout
Flexibility : The biggest advantage of fluid layout is its flexibility. It can easily adapt to display devices of different sizes, providing a better user experience.
Ease of maintenance : Using percentages instead of fixed pixels makes maintenance easier when adapting to new devices or screen sizes.
Accessibility : Fluid layout provides better accessibility as it allows users to resize the browser window according to their needs.
Fluid Layout Challenges
Although fluid layout offers many advantages, it also faces some challenges in practical applications:
Difficulty of control: Managing fluid layouts is more complex than fixed layouts, especially in complex interface designs where it is difficult to ensure that all elements perform well on different screen sizes.
Adaptation of media content : The adaptation of fixed-size media content such as pictures and videos in a fluid layout may cause problems, such as distortion or layout breakage.
Techniques for implementing fluid layouts
To achieve a fluid layout, you need to use a series of CSS properties, mainly the percentage settings of width, maximum width, and minimum width. Here are a few key CSS properties:
Percent width :
.container { width: 80%; }
The width of such
.container
a class will be 80% of the width of its parent element, automatically adjusting as the viewport changes.Media Queries : Media queries are an integral part of fluid layout, allowing different style rules to be applied based on different screen sizes.
@media (max-width: 600px) { .container { width: 100%; } }
When the screen width is less than 600px,
.container
the width will occupy the entire viewport.flexbox : Flexbox provides another way to create fluid layouts, especially when complex layouts and alignments are involved.
COPY
COPY
.flex-container { display: flex; justify-content: space-between; }
Fluid layout and responsive design
Fluid layout is often used together with responsive design, but there are differences between the two. Responsive design includes not only fluid width;
Includes responsive media queries, adaptable image solutions and possible layout changes. Fluid layouts are often part of a responsive design strategy that focuses on making the width of the layout flexible.
Practical examples of fluid layouts
Consider a typical web page layout with a header, three columns of content, and a footer. In a fluid layout, these elements can be set as follows:
.header, .footer {
width: 100%;
height: 50px;
}
.sidebar {
width: 20%;
float: left;
}
.main-content {
width: 60%;
float: left;
}
.aside {
width: 20%;
float: right;
}
This layout ensures that the sidebar and main content area always maintain proper proportions regardless of changes in viewport size. When the screen size decreases, the layout can be adjusted through media queries, such as stacking these components on small screens.
Flex layout
Flexbox is an efficient CSS layout mode suitable for one-dimensional layout, which can control the alignment, direction, order and size of items in the container. The following introduces in detail the basic knowledge of Flex layout, container properties, project properties, and how to use Flex to implement mobile layout and Holy Grail layout.
Flex Basics
Flex layout allows items within a container to dynamically allocate additional space and resize without using fixed dimensions. When using Flex layout, you first need to set it on the parent container display: flex;
so that its child elements become Flex items.
Flex container properties
display
:display: flex;
: Define a standard Flex container.display: inline-flex;
: Define an inline Flex container.
flex-direction
:Control the arrangement direction of Flex items.
Values:
row
(default, landscape),row-reverse
(reverse landscape),column
(portrait),column-reverse
(reverse portrait).
justify-content
:Sets the alignment of the item on the main axis.
Values:
flex-start
,flex-end
,center
,space-between
(aligned on both ends),space-around
(dispersed alignment),space-evenly
(evenly distributed).
align-items
:Sets how items are aligned on the cross axis.
Values:
flex-start
,flex-end
,center
,baseline
(baseline alignment),stretch
(default, stretch to fill container).
flex-wrap
:Control whether the container is single-line or multi-line, and how overflowing items are handled.
Values:
nowrap
(default, no line wrapping),wrap
(line wrapping),wrap-reverse
(reverse line wrapping).
Flex project properties
flex-grow
:Defines the magnification of the item.
The default is
0
that items will not be enlarged if there is remaining space.
flex-shrink
:Defines the reduction ratio of the project.
The default is
1
that if there is not enough space, the project will shrink.
flex-basis
:Defines the default size of a project before excess space is allocated.
The value can be
auto
(the original size of the project) or a specific value (such as%
,px
,em
etc.).
flex
:flex
Abbreviation for isflex-grow
,flex-shrink
and .flex-basis
Common usage:
flex: 1;
Indicates that the item will equally divide the remaining space.
align-self
:Allows individual items to have different alignment than other items, overridable
align-items
properties.The values are the same
align-items
.
Flex completes mobile layout
Use Flex layout to easily create responsive mobile interfaces. For example, a typical navigation bar can be set up to stack on small screens and appear horizontally on large screens:
.navbar {
display: flex;
flex-direction: row; /* 水平布局 */
flex-wrap: wrap; /* 在需要时换行 */
}
.nav-item {
flex: 1; /* 等分空间 */
}
@media (max-width: 600px) {
.navbar {
flex-direction: column; /* 堆叠导航项 */
}
}
Flex Completes Holy Grail Layout
The Holy Grail layout is a three-column layout, with the middle column rendering first and the two side columns being fixed or adjusted based on the viewport width. Implemented using Flex
The Holy Grail layout is as follows:
.container {
display: flex;
justify-content: space-between;
}
.main {
flex: 1; /* 主内容区占据大部分空间 */
}
.sidebar {
flex-basis: 150px; /* 侧边栏宽度 */
}
In actual applications, more style rules may need to be added to meet complex design requirements.
rem and vw layout
In responsive web design, developers often need to use multiple CSS units to adapt to different screen sizes. rem
and vw
are two very popular units, each with unique advantages that can help developers create more flexible and adaptable layouts. This article will take an in-depth look at the characteristics of both units, how they can be used, and how to use them together to achieve the best layout results.
rem unit
rem
(Root EM) is a relative length unit, relative to the font size of the root element (HTML element). This means that no matter how deeply nested the element is, rem
the units are relative to the font size of the root element, not the parent element.
Advantages of rem
Consistency : Use
rem
to ensure that the font size is consistent throughout the page, making it easy to control and modify.Easy to maintain : Adjusting the font size of the root element can quickly affect
rem
all elements using the unit, making it easy to adjust the layout.Accessibility : Suitable for scenarios where the layout needs to be adjusted according to the default font size of the user's browser to improve the accessibility of the website.
Examples of using rem
In CSS, it is common to set the font size of HTML elements to a base value, for example:
html {
font-size: 16px;
}
Next, use rem
units to size other elements:
h1 {
font-size: 2rem; /* 32px */
}
p {
font-size: 1rem; /* 16px */
}
.container {
padding: 1rem; /* 16px */
}
vw unit
vw
(Viewport Width) is the percentage unit of the viewport width. 1vw
Equal to 1% of the viewport width. This makes vw
units ideal for creating layouts that maintain a consistent visual experience across different screen sizes.
Advantages of vw
Flexibility :
vw
It can be very flexible to automatically adjust the size of elements according to changes in the size of the viewport.Responsive design : Very suitable for responsive design, which can reduce the use of media queries and simplify CSS code.
Example of using vw
Set the element width to a certain percentage of the viewport, for example:
.header {
width: 100vw; /* 视口宽度的100% */
}
.banner {
height: 50vw; /* 视口宽度的50% */
}
Such a setup ensures that elements resize proportionally regardless of changes in viewport width.
Used with rem and vw
Using rem
together vw
provides better layout control on different screen sizes. For example, you can set the font size of the root element as a percentage of the viewport width, and then use rem
units to set the size of specific elements:
html {
font-size: 2vw;
}
When set this way, 1rem
it will be equal to 2% of the viewport width. In this way, not only the font size of the element will be dynamically adjusted as the viewport changes, but the associated spacing and size will also be adjusted accordingly.
Practical application
In practical applications, rem
and vw
units are often used to achieve fully flow designs. For example, you can set a minimum and maximum width for the body of the web page to ensure that the content is still readable on very small or very large screens:
.body {
width: 80vw;
max-width: 1200px;
min-width: 300px;
margin: 0 auto; /* 居中显示 */
}
rem
In addition, using and in combination with media queries vw
, the layout can be further optimized to adapt to different breakpoints:
@media (max-width: 600px) {
html {
font-size: 4vw; /* 在小屏幕上增大基准字体大小 */
}
}
Mobile version advanced
1. Responsive layout
Responsive layout is a web design approach that aims to enable websites to adapt to various screen sizes and resolutions. Using fluid grids, flexible images, and media queries are key techniques for implementing responsive design.
Fluid Grid : Use percentages instead of fixed pixels to define element widths, ensuring layout adaptability across different devices.
Flexible images : Use relative units or
max-width
set the image size to 100% to ensure that the image adapts within the container.Media queries : CSS media queries allow applying different style rules based on different device characteristics (such as screen width, resolution, etc.).
Example:
COPY
COPY
.container {
width: 80%;
max-width: 1200px;
min-width: 300px;
margin: auto;
}
img {
max-width: 100%;
height: auto;
}
@media (max-width: 768px) {
.sidebar {
display: none;
}
}
2. Grid layout
CSS Grid Layout is a powerful two-dimensional layout system designed to completely change the way we create complex layouts on the web. Grid allows developers to design clearly defined row and column layouts and control the position and size of HTML elements through intuitive layout methods. The following is a detailed analysis of the core concepts, functions, technical applications and solutions to common problems of Grid layout.
The core concept of Grid grid layout
CSS Grid Layout provides a way to lay out content through rows and columns. Its main concepts include:
Container (Grid Container) : Declare an element as a Grid container, and the child elements of the element will become Grid Items.
Items (Grid Items) : direct child elements of the Grid container.
Rows (Grid Rows) : Horizontal tracks of the Grid.
Columns (Grid Columns) : Grid's vertical track.
Grid Lines : The dividing lines that form the grid structure and are used to position grid items.
Grid Tracks : Row or column spaces between two adjacent grid lines.
Grid Cell : The smallest unit of the grid, consisting of two adjacent row grid lines and two adjacent column grid lines.
Grid Area : An area containing one or more grid cells.
Implement Grid layout
To use Grid layout, you first need to declare a container element as a Grid container, which is achieved by display
setting the container's properties to grid
or inline-grid
.
COPY
COPY
.container {
display: grid;
}
Define rows and columns
Use the grid-template-rows
and grid-template-columns
properties to define row and column dimensions. For example, create a grid with three rows and three columns, with each cell sized 100px:
.container {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px 100px;
}
For more flexibility in handling different screen sizes, you can use fr
units, which are flexible units that represent a portion of the available space. In the following example, each column takes up a share of the available space:
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
Use grid lines to position items
Grid items are placed in the order of the document flow by default, but their position can be precisely controlled through grid-column
and . grid-row
These properties specify which grid line the item should start from and end at.
.item {
grid-column: 1 / 3;
grid-row: 1 / 2;
}
The above code means that the item will occupy the first two columns of the first row.
Create complex grid layouts
Complex grid layouts can be created by combining row and column definitions. For example, a layout with columns of different sizes:
.container {
display: grid;
grid-template-columns: 2fr 1fr 1fr;
}
In this layout, the first column is twice as wide as the other two columns.
Advanced features of grid layout
grid gap
grid-gap
Property (now recommended gap
) can define the spacing between items. This property can accept two values, the first value sets the row gap, and the second value sets the column gap.
.container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px 20px;
}
Grid auto layout
Grid provides powerful automatic layout capabilities, and grid-auto-flow
the direction of automatically placed items can be controlled through attributes. The default value isrow
, can also be set to column
, or even dense
to try to fill in the gaps left in the earlier layout.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-flow: dense;
}
Solve common problems
When actually using Grid layout, developers may encounter some problems, such as compatibility issues, layout misalignment, etc. Strategies for dealing with these issues include:
- Compatibility : Although most modern browsers support Grid layout, fallback solutions are still required in some older browsers. Functional queries can be used
@supports
to provide alternative styles:
@supports (display: grid) {
.container {
display: grid;
}
}
@supports not (display: grid) {
.container {
display: flex;
}
}
- Debugging : Use the browser's developer tools to check the Grid layout. Most modern browsers provide visual Grid layout debugging tools.
3. Frequently Asked Questions about Mobile Web Development
Challenges faced by mobile web development include touch event processing, device and browser compatibility, changes in network conditions, etc.
Touch optimization : Make sure buttons and links are large enough for touch.
Viewport configuration : Configure
<meta name="viewport">
labels appropriately to improve the visual experience.Performance optimization : compress resources, merge files, reduce HTTP requests, and improve loading speed.
4. Mobile events
The mobile event processing is different from the desktop environment, mainly the processing of touch events. Common touch events include touchstart
, touchmove
, touchend
etc.
Event listening : Monitor these events to provide interactive feedback, such as sliding menus and picture carousels.
Prevent default behavior : such as preventing page scrolling
e.preventDefault()
, especially when handling swipe interactions.
Example:
document.addEventListener('touchstart', function(e) {
console.log('Touch started');
}, false);
5. Mobile Web development performance optimization
Performance optimization is key to improving user experience. Here are a few optimization tips:
Image optimization : Load images on demand using appropriate formats and compression.
minimize
Resources: Reduce CSS and JavaScript file size, use compression tools.
Caching strategy : Make use of browser cache and set reasonable cache headers.
Server-side response : Use CDN to distribute content and reduce server response time.
<link rel="stylesheet" href="style.min.css">
<script src="app.min.js"></script>
Subscribe to my newsletter
Read articles from Kohki Chau directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by