The layout of CSS Grid is simple and efficient. The first step is to set the container as a grid container, which is implemented through display: grid; The column width and row height can then be defined, such as grid-template-columns and grid-template-rows. 1. Use fr units to flexibly allocate space, such as 1fr or 2fr. 2. The repeat() function simplifies repeated values, such as repeat(3, 1fr) to create third-class columns. 3. The named area defines the structure through grid-template-areas, and cooperates with the grid-area attribute of the child element. 4. Use gap or row-gap/column-gap to set the spacing to not affect the edge distance. Master these core concepts and make the layout easier.
Using CSS Grid to make layouts is actually much simpler than you think, especially now that mainstream browsers support it. It doesn't struggle with float and inline-block as before. Grid is designed specifically for two-dimensional layouts, with both rows and columns being controlled, and it's easier to be responsive.
Setting up containers is the first step
If you want to use Grid, you must first set an element as the grid container:
.container { display: grid; }
As long as this sentence is added, its direct child elements will automatically become grid items. At this time, the column width and row height have not been specified, and the column width will be arranged in a row by default.
You can add dot styles to define column width and row height, for example:
-
grid-template-columns
: defines the width of each column -
grid-template-rows
: defines the height of each row
For example:
.container { display: grid; grid-template-columns: 200px 1fr 1fr; }
The above writing method is three columns: the first column is fixed 200px, and the latter two columns distribute the remaining space evenly.
Flexible allocation of space using fr units
fr
is a unit unique to Grid, representing "a portion of available space". For example, if you want two columns to divide the space bipartitely, you can write it like this:
grid-template-columns: 1fr 1fr;
If you want one to account for 2/3 and the other to account for 1/3:
grid-template-columns: 2fr 1fr;
This writing method is particularly useful when doing responsive forms. You don’t need to care about the total width, the browser will automatically calculate it.
Another commonly used function is repeat()
, which can avoid repeated writing of the same value:
grid-template-columns: repeat(3, 1fr);
This means creating three monospace columns.
Use named areas to make the structure clearer
If you want to create a basic structure of a web page, such as header, sidebar, main, footer, etc., you can use the method of naming the region:
.container { display: grid; grid-template-areas: "header header" "sidebar main" "footer footer"; }
Then add the corresponding name for each child element:
.header { grid-area: header; } .sidebar { grid-area: sidebar; } .main { grid-area: main; } .footer { grid-area: footer; }
This method is particularly suitable for the overall layout of the page, with clear logic and convenient modification.
Don't forget to adjust the row spacing and column spacing
By default, there are no gaps between grids. If you want to set the spacing, you can use these two properties:
-
gap
: set the interval between rows and columns at the same time -
row-gap
/column-gap
: set rows or columns respectively
For example:
.container { gap: 20px; }
Or write separately:
.container { row-gap: 10px; column-gap: 20px; }
Note: The gap will not affect the distance from the edge of the container to the first/last grid. If you need extra margins, use padding
or margin
.
Basically that's it. There are not many core concepts in CSS Grid, but they are very powerful when combined. At first, it may feel a bit complicated, and you can find out how easy it is by trying it a few more times. It is not complicated, but it is easy to ignore details, such as forgetting to set containers, confusing fr and px, or not handling the spacing well - pay attention to these small places and the layout will be smooth.
The above is the detailed content of How to use CSS Grid for layout. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ToimplementdarkmodeinCSSeffectively,useCSSvariablesforthemecolors,detectsystempreferenceswithprefers-color-scheme,addamanualtogglebutton,andhandleimagesandbackgroundsthoughtfully.1.DefineCSSvariablesforlightanddarkthemestomanagecolorsefficiently.2.Us

The topic differencebetweenem, Rem, PX, andViewportunits (VH, VW) LiesintheirreFerencepoint: PXISFixedandbasedonpixelvalues, emissrelative EtothefontsizeFheelementoritsparent, Remisrelelatotherootfontsize, AndVH/VwarebaseDontheviewporttimensions.1.PXoffersprecis

Choosing the correct display value in CSS is crucial because it controls the behavior of elements in the layout. 1.inline: Make elements flow like text, without occupying a single line, and cannot directly set width and height, suitable for elements in text, such as; 2.block: Make elements exclusively occupy one line and occupy all width, can set width and height and inner and outer margins, suitable for structured elements, such as; 3.inline-block: has both block characteristics and inline layout, can set size but still display in the same line, suitable for horizontal layouts that require consistent spacing; 4.flex: Modern layout mode, suitable for containers, easy to achieve alignment and distribution through justify-content, align-items and other attributes, yes

CSSHoudini is a set of APIs that allow developers to directly manipulate and extend the browser's style processing flow through JavaScript. 1. PaintWorklet controls element drawing; 2. LayoutWorklet custom layout logic; 3. AnimationWorklet implements high-performance animation; 4. Parser&TypedOM efficiently operates CSS properties; 5. Properties&ValuesAPI registers custom properties; 6. FontMetricsAPI obtains font information. It allows developers to expand CSS in unprecedented ways, achieve effects such as wave backgrounds, and have good performance and flexibility

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

CSSgradientsenhancebackgroundswithdepthandvisualappeal.1.Startwithlineargradientsforsmoothcolortransitionsalongaline,specifyingdirectionandcolorstops.2.Useradialgradientsforcirculareffects,adjustingshapeandcenterposition.3.Layermultiplegradientstocre

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

In Vue, provide and inject are features for directly passing data across hierarchical components. The parent component provides data or methods through provide, and descendant components directly inject and use these data or methods through inject, without passing props layer by layer; 2. It is suitable for avoiding "propdrilling", such as passing global or shared data such as topics, user status, API services, etc.; 3. Note when using: non-responsive original values ??must be wrapped into responsive objects to achieve responsive updates, and should not be abused to avoid affecting maintainability.
