CSS Grid PDF
Document Details
Uploaded by PatientRubidium
Tags
Summary
This document provides a comprehensive tutorial on CSS Grid Layout. It explains various concepts such as creating grid containers, defining rows and columns, adding more columns using grid-template-columns, different grid examples, and more. The document uses diagrams and code examples to illustrate the properties. This tutorial also discusses responsive design concepts.
Full Transcript
GRID The CSS Grid Layout module, is a two-dimensional grid- based layout system, with flexible rows and columns. In a regular table rows and columns would be defined in HTML, with CSS Grids these are defined purely in CSS. Grids are often used for galleries or newspapers as they provide an easy way...
GRID The CSS Grid Layout module, is a two-dimensional grid- based layout system, with flexible rows and columns. In a regular table rows and columns would be defined in HTML, with CSS Grids these are defined purely in CSS. Grids are often used for galleries or newspapers as they provide an easy way to create flexible layouts like this: To create a grid container, set the element’s display property to grid (container becomes a block element) or inline-grid (container becomes an inline element). LLL HTML One Two Three CSS.grid { display: grid; }.item { background: #ffcc00; border: 2px solid black; padding: 10px; } One Two Three RRR By default, CSS Grid uses a single column, and will create rows as needed, based on the number of children. By default, the height of the grid parent is determined by its children. It grows and shrinks dynamically. If we give the grid container a fixed height, the area would be devided into equally-sized rows: CSS.grid { display: grid; height: 300px; }... One Two Three LLL GRID CONSTRUCTION If we want to add more columns, we can specify them with the grid-template-columns property. CSS.grid { display: grid; grid-template-columns: 25% 75%; }... By passing two space-seperated values to the property — 25% and 75% — We’re telling the CSS Grid algorithm to slice the element up into two columns: One Two Columns can be defined using any valid CSS length or percentage value (px, rem, etc.). Additionally, we also gain access to a new unit, the fr (fraction) unit: CSS.grid { display: grid; grid-template-columns: 1fr 3fr; } RRR 4 fr One Two 1 fr 3 fr (1/4 = 25%) (3/4= 75%) fr-based columns are flexible, so columns won't shrink below their minimum content size, even if that means breaking the proportions. Consider following example: grid-template-columns: grid-template-columns: 25% 75%; 1fr 3fr; Keep in mind that percentages in Grid are calculated based on the total grid area. If two columns take up 100% of the container's width and can't shrink, adding a 12px gap will force the columns to overflow beyond the container. The fr unit is calculated based on the extra space. In this case, the extra space has been reduced by 12px, LLL for the gap. grid-template-columns: grid-template-columns: 25% 75%; 1fr 3fr; gap: 12px; gap: 12px; Let’s add another child to our two-column grid from before: One Two Three Our grid gains a second row! The grid ensures that every child has its own grid cell. If we want to define the rows explicitly, we could use grid-template-rows : CSS.grid { height: 500px; display: grid; grid-template-columns: 1fr 3fr; grid-template-rows: 100px 1fr; gap: 20px; } RRR 1fr 3fr One Two 100px Three Four 1fr (rest of the free space) THE REPEAT HELPER Let’s say we’re building the layout of a calendar: Now we just have to structure the 7 column grid: grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr; Typing all 1fr’s out is a bit repetitive and annoying, luckily there is a repeat function which will do the copy/pasting: grid-template-columns: repeat(7, 1fr); we want 7 columns, LLL each being 1fr Try to build a grid calendar yourself! Once you are done or need help you can check out this example calendar: HTML 1 2... 31 CSS.calendar { display: grid; grid-template-columns: repeat(7, 50px); grid-template-rows: repeat(5, 50px); gap: 10px; width: 400px; }.day { display: flex; justify-content: center; align-items: center; background-color: #ffcc00; padding: 10px; border-radius: 4px; } RRR Result 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ASSIGNING CHILDREN By default, our Grid will assign each child to the first unoccupied grid cell. But we can assign our items to whichever cells we want! Let’s say we have a 4x3 grid: 1 2 3 4 5 1 2 3 4 Confusingly, a 4-column grid actually has 5 column lines. When we assign a child to our grid, we LLL anchor them using these lines. The grid-row and grid-column properties allow us to specify which track(s) our grid child should occupy. To place a child in a specific row or column, simply use its number. CSS.item { grid-column: 3; grid-row: 2; } 1 2 3 4 5 1 2 3 4 RRR Grid children can also stretch across multiple rows and columns. The syntax for this uses a slash to distinguish start and end line: CSS.item { grid-column: 1 / 4; grid-row: 2 / 4; } 1 2 3 4 5 1 2 3 4 We can also count in the opposite direction, with negative line numbers, from right to left: CSS.item { grid-row: 2; grid-column: 1 / -1; LLL } 1 2 3 4 5 (-1) 1 2 3 4 GRID AREAS Let’s say we would want to create following layout: Header Sidebar Content Ofcourse we could define a 2 column / 2 row grid and assign each child with specifying the column / row, however there is a better way to do that. With CSS Grid, we can easily divide our layout into named areas, giving each section a clear purpose and structure. RRR Here’s what named areas look like: CSS.parent { display: grid; grid-template-columns: 2fr 5fr; grid-template-rows: 60px 1fr; grid-template-areas: 'sidebar header' 'sidebar content'; }.child { grid-area: header; } Child Sidebar Content Like before, we're defining the grid structure, but this time we add the grid-template-areas property which names each part of the grid. The first row has a sidebar and header, while the second row has a sidebar and LLL a content. grid-area assigns the child to a area. It’s like saying, "This element belongs to the header section of the grid". Min... Max... MINIMAX! The values inside the minmax(min, max) function, we can specify a minimum and maximum width / height between which the column width / row height can vary based on the available space. Minmax is great for smaller viewports. CSS.parent { display: grid; grid-template-rows: repeat(2, 150px); grid-template-columns: minmax(200px, 300px) 100px repeat(2, minmax(50px, 75px)); } 150px 150px 200px-300px 100px 50px-75px RRR autofill and autofit The auto-fill keyword in CSS grids automatically creates as many grid tracks (rows or columns) as will fit within the container. If there's extra space, it even adds empty tracks. HTML 1 2... 6 CSS.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 10px; padding: 10px; border: 2px solid #ddd; }.item { background-color: #ffcc00; padding: 20px; text-align: center; } LLL Result 1 2 3 4 5 6 Resize the browser window to see how the grid adapts, creating extra empty tracks if space is available. The auto-fit keyword, on the other hand, adjusts the grid items so that they fill the available space. Let’s replace the auto-fill with auto-fit from last example: CSS.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));... } On smaller viewports: On wider viewports: 1 1 2 3 2 4 5 6 3 RRR ALIGNING COLUMS So far our columns and rows stretch to fill the entire grid container. Just like with flexbox we can align our grid items. Let's say we define two columns that are each 100px wide. As long as the grid parent is larger than 200px, there will be some dead space at the end. The spacing of the columns can be adjusted using the justify-content property: CSS.grid { display: grid; grid-template-columns: 50px 50px; justify-content: center; } Result 1 2 3 The big difference is that we're aligning the columns, not the items themselves. LLL If we want to align the items themselves within their columns, we can use the justify-items property: CSS.grid { display: grid; grid-template-columns: 100px 100px; justify-content: space-between; justify-items: center; } One Two Three Four 100px 100px We can even control the alignment of a specific grid child using justify-self : you could also use start, center or stretch CSS.one { justify-self: end; } RRR One Two Three Four ALIGNING ROWS CSS Grid provides an additional set of properties to align stuff in the vertical direction. align-content is like justify-content, but it affects rows instead of columns. Similarly, align-items is like justify- items, but it handles the vertical alignment of items inside their grid area, rather than horizontal. CSS.grid { display: grid; justify-content: center; justify-items: stretch; align-content: end; align-items: end; } LLL Col 1 Col 2 Row 1 One Two Row 2 Three Four Let’s set align-content: start; align-items: center; Col 1 Col 2 Row 1 One Two Row 2 Three Four You can remember the properties as follows: justify — deals with columns align — deals with rows content — deals with the grid structure items — deals with items inside the grid structure RRR Along with justify-self, there's also align-self , which controls a single grid item's vertical position within its cell. TWO-line centering shorthand Using place-content , we can center a child within a container, both horizontally and vertically: CSS.grid { display: grid; place-content: end; } Col 1 Row 1 Child It’s the same as saying:.grid { justify-content: end; align-content: end; } LLL BUILDING A CALCULATOR LAYOUT After learning all these grid properties, it’s time to put them into action by building the layout of a calculator project using CSS Grid. Here’s what we want to achieve: 4x6 grid Result stretches from the first grid line to the last “0” should stretch two grid lines Result’s text should be right aligned I beg you to take a moment and try building the calculator layout yourself! Hands-on practice helps you understand the concepts better and makes them stick. One solution of many is shown on the next pages. If you want to practice your grid skills even more, check out cssgridgarden.com RRR HTML 0 AC +/- % ÷ 7 8 9 × 4 5 6 - 1 2 3 + 0. = LLL CSS.calculator { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; max-width: 300px; margin: 2rem auto; background-color: #f0f0f0; border-radius: 10px; padding: 15px; }.display { grid-column: 1 / -1; background-color: #fff; border: 1px solid #ccc; padding: 10px; text-align: right; font-size: 1.5rem; }.btn { background-color: #e0e0e0; border: none; padding: 15px; cursor: pointer; font-size: 1rem; }.btn-zero { grid-column: 1 / 2; } RRR RESPONSIVE WEB DESIGN Visitors will come with different devices and view your site on different screens, so your design must adjust to fit a range of different sized screens. iPhone 16 Pro Max Thinkpad T490 6.9 inches 14 inches 2868 x 1320 pixels 1920 x 1080 pixels The size of a user's screen affects how big they can open their windows and how much LLL of the page they will see at once SCREEN RESOLUTION Resolution refers to the number of pixels displayed on a screen, formatted as width x height. Some devices have higher resolutions than others. A higher resolution means more pixels are packed into the same space, resulting in sharper images and text. Common screen resolutions are: 1920 x 1080 (Full HD) 2560 x 1440 (WQHD, “2K”) 3840 x 2160 (Ultra HD, “4k”) 360 x 800 (~ 10% of mobile phones use this resolution) ASPECT RATIO Along with resolution, aspect ratio describes the proportion between the width and height of a screen. It shapes how content fits. Responsive designs rely on balancing resolution and aspect ratio. 16:9 1:1 9:16 RRR WEBPAGE LAYOUTS Because screen sizes and display resolutions vary so much, websites are often designed to be around 1024 pixels wide. There are two main types of CSS layouts... FIXED WIDTH LAYOUTS Fixed width layout designs do not change size as the user increases or decreases the size of their browser window. Measurements tend to be given in pixels. If the screen is too small, horizontal scrollbars appear; If it’s too large, there’s empty space around the content. px px px LLL PROS CONS Easy to plan and Poor adaptability to implement different screen sizes Predictable structure Can’t create true responsive designs FLUID LAYOUTS Fluid layouts use percentage-based widths, allowing the design to adapt to the browser’s width. They tend to use percentages. Content stretches or shrinks to use the available space, making it better for different screen sizes. % % % PROS CONS Maximizes screen space More complex to create Supports responsive May limit creative designs freedom RRR WAYS OF KEEPING A SITE RESPONSIVE SETTING THE VIEWPORT The viewport is the user's visible area of a web page. We can control the viewport using the following tag (you should include it in the for all of your sites): width=device-width sets the width of the page to follow the screen-width of the device initial-scale=1.0 sets the initial zoom level when the page loads Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo Lorem ipsum dolor sit consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie amet, consectetuer consequat , vel illum dolore eu feugiat nulla adipiscing elit, sed diam facilisis at vero eros et accumsan et iusto odio nonummy nibh euismod dignissim qui blandit praesent luptatum zzril tincidunt ut laoreet delenit augue duis dolore te feugait nulla dolore aliquam erat Without the tag With the tag LLL RESPONSIVE UNITS Responsive units are needed for making layouts that adapt to different screen sizes. We’ve already talked about %, rem, and em, but there are also a few more. The vh (viewport height) unit is based on the height of the viewport. 1vh is equal to 1% of the viewport height. The vw (viewport width) unit is based on the width of the viewport. 1vw is equal to 1% of the viewport width. Most websites have a “hero” section, a relatively large area that immediately shows up on the screen. It should grab attention and create a strong first impression. Let’s create a hero section that is 100vh tall: HTML John Pork I create stunning websites... Contact Me RRR CSS body { font-family: Arial, sans-serif; background-color: #f4f4f9; font-size: 1.6rem; }.hero { display: flex; align-items: center; justify-content: space-evenly; height: 100vh; padding: 0 2rem; max-width: 1024px; margin: 0 auto; }.hero-content h1 { font-size: 3.8rem; color: #333; }.hero-content p { font-size: 2rem; color: #666; LLL margin-bottom: 0.8rem; }.hero-button { padding: 0.8rem 1.6rem; font-size: 1.6rem; background: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer; }.hero-image img { max-width: 100%; border-radius: 10px; } Result John Pork I create stunning websites... Contact Me RRR CSS also has a special calc(expression) function for doing math. You calculate with different units (like px, %, rem, em, etc.) and operators (+, -, *, /). For example: width: calc(10px + 100px); width: calc(100% - 30px); width: calc(2rem * 5); RESPONSIVE IMAGES Keeping our images responsive will adjust them to fit the size of the screen or container. Here’s a example: CSS img { width: 100%; height: auto; } Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore aliquam erat LLL If you want an image to scale down if it has to, but never scale up to be larger than its original size, use max-width: CSS img { max-width: 100%; height: auto; } Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed We could also use max-width, if we wanted to restrict a responsive image to a maximum size: CSS img { width: 100%; max-width: 400px; height: auto; } RRR If we want to set the aspect ratio of an image ourselves, we could use the aspect-ratio property: CSS img { aspect-ratio: 1 / 1; width: 200px; } 200px 200px If both aspect-ratio and width are defined, the height automatically adjust to maintain the specified aspect ratio. LLL MEDIA QUERIES Media Queries allow you to apply CSS styles depending on a device's media type or other characteristics such as screen resolution, orientation or size of the viewport. Here’s what a media query might look like: @media screen (min-width: 300px) and (max-width: 700px) Media feature Media type Operator At-rule Media feature At-rule: start of a media query, the media rule is just one of many @rules (e.g. @font-face on page 180) Media type: specifies the type of device targeted. screen - matches devices with a screen print - matches print preview mode all - matches all devices Media feature: the type of media we’re trying to match. Commonly used features: orientation - Landscape or portrait max-height - Maximum height of viewport min-height - Minimum height of viewport RRR height - Height of viewport (including scrollbar) max-width - Maximum width of viewport min-width - Minimum width of viewport width - Width of viewport (including scrollbar) prefers-color-scheme - Detects if the user prefers a light or dark color scheme. Values: light, dark Operator: logical operators which basically state that “if” the following types and features are matches, then do some stuff. Possible operators: and @media screen (min-width: 320px) and (max-width: 768px) {... } or @media screen (min-height: 800px) or (max-width: 768px) {... } not @media not screen and (max-width: 768px) {... } Inside {... } we can put in actual CSS styles. For example, if we wanted to have a different background color for smaller device screens such as phones we could say: LLL CSS body { background: red; } @media screen and (max-width: 768px) { body { background: blue; } } Media queries are great with flexbox! On larger screens, items can be in a row, but on smaller ones, they might overflow. A media query can change the flex direction to 'column' to stack items vertically. Give it a try! RRR HTML Item 1 Item 2 Item 3 CSS.container { display: flex; gap: 1rem; }.item { background: orange; padding: 1rem; text-align: center; flex: 1; } @media (max-width: 768px) {.container { flex-direction: column; }.item { color: white; background: blue; } LLL } Item 1 Item 1 Item 2 Item 3 Item 2 Item 3 We could also define media queries outside of a CSS file, like inside the HTML element when linking CSS files. In this case widescreen.css will load if the screen is 900px or wider. If the screen is 600px or smaller smallscreen.css will load. It is more common to include all media queries in a single stylesheet, altough this approach would be more network efficient, as only the CSS file the device needs will load. RRR A BREAKPOINT is a specific point at which the layout of a website changes to adapt to different screen sizes. Because there are so many devices, we can’t define fixed breakpoints for everyone of them. A better approach is to adjust the design when content starts to break, like when line lengths become too long or a sidebar gets squashed and unreadable. Common breakpoints where this happens: