Lesson 24-CSS Layout and Positioning Application Solutions

Float layout

The core of CSS3 float layout is to use the float property to move elements out of the document flow, arrange elements by floating left and right, and combine the clear property or clear float techniques (such as the pseudo-element method here) to deal with the side effects of floating. Although float layout is still practical in some simple layouts, for more complex layout requirements, such as flexible grid systems, responsive design, etc., it is recommended to use CSS3’s Flexbox or Grid layout model.

Float

  • float is a property in CSS that specifies how an element should be positioned relative to the elements around it.
  • Acceptable values ​​include left, right, none, and inherit. Setting float: left or float: right will cause the element to be out of the normal document flow and move in the corresponding direction until it encounters the edge of the parent container or another floating element.

Behavior of floating elements

  • Floating elements will change the layout of themselves and surrounding non-floating elements:
  • Floating elements will move as far as possible in the specified direction until they encounter other floating elements or the edge of the container.
  • Non-floating elements flow around floating elements as if the floating elements do not exist in the normal document flow.
  • If all child elements within an element are floated, the element may lose height because the floating elements no longer affect the height calculation of their parent elements.

Clearing floats

Clearing floats is a key point that must be paid attention to when using floating layouts. When an element is floated, it may cause the height of the sibling elements or parent containers behind it to collapse. To solve this problem, there are several ways:
Use the clear property: set clear: left, clear: right, or clear: both for the affected elements to prevent them from appearing on the same side of the floating element.
Use clearfix hack or pseudo-element clearing method: Add the following style to the parent container of the floating element:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Floating layout example</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <div class="container">
            <aside class="sidebar">
                <h2>Sidebar</h2>
                <!-- Sidebar content -->
            </aside>
            <main class="content">
                <h1>Main Content</h1>
                <!-- Main content -->
            </main>
        </div>
    </body>
</html>
/* Basic style settings */
body {
    font-family: Arial, sans-serif;
    margin: 0;
}

.container {
    /* Make sure the container contains the floating elements */
    overflow: hidden;
}

/* Sidebar style */
.sidebar {
    float: left;
    width: 250px; /* Sidebar fixed width */
    padding: 20px;
    background-color: #f5f5f5;
}

/* Content area style */
.content {
    /* Float on the right side of the sidebar */
    float: right;
    /* Adapt to the remaining width */
    width: calc(100% - 250px); /* Subtract the sidebar width */
    padding: 20px;
    background-color: #ffffff;
}

/* Clear the floating effect and make sure the container contains the height of the floating elements */
.container::after {
    content: "";
    display: block;
    clear: both;
}
  1. HTML structure: Create a basic HTML document structure, including the <head> section (introducing the CSS file) and the <body> section. Define a .container in <body> as the container for the overall layout, which contains two sub-elements: .sidebar (sidebar) and .content (main content area).
  2. CSS basic styles: Set common styles, such as fonts, page margins, etc. Here, overflow: hidden is also set for .container to ensure that the container can wrap the floating sub-elements.
  3. Sidebar style: Set float: left for .sidebar to float to the left, and specify a fixed width. At the same time, add padding and background color to enhance the visual effect.
  4. Content area style: Set float: right for .content to float to the right, and use the calc() function to calculate the width as the container width minus the sidebar width to achieve adaptive effect. Also add padding and background color.
  5. Clear floats: Use the :after pseudo-element to create an empty block-level element after the .container container, and set clear: both to clear the floats, ensuring that the container can properly wrap the floating child elements and avoid height collapse problems.

Absolute layout

Absolute positioning in CSS3 is a layout method that allows you to move elements out of the normal document flow and place them precisely at a certain position on the page. Absolute positioning is based on its nearest positioned ancestor element (that is, an element with a non-default position attribute). If there is no positioned ancestor element, it is positioned relative to the browser viewport.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Absolute Layout Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <header class="header">
        <!-- Header content -->
        </header>
        <main class="content">
        <section class="overlay-box">
            <h2>Overlay Box</h2>
            <!-- Overlay content -->
        </section>
        <!-- Main content -->
        </main>
        <footer class="footer">
        <!-- Bottom content -->
        </footer>
    </div>

</body>

</html>
/* Basic style settings */
body {
    font-family: Arial, sans-serif;
    margin: 0;
}

.container {
    position: relative; /* Make .container a positioning reference for absolutely positioned elements */
}

/* Absolutely positioned element style */
.overlay-box {
    position: absolute; /* Set to absolute positioning */
    top: 50%; /* 50% offset from the top of the nearest positioned ancestor element */
    left: 50%; /* 50% offset from the left of the nearest positioned ancestor element */
    transform: translate(-50%, -50%); /* Use translate for center alignment */
    width: 300px;
    padding: 20px;
    background-color: rgba(0, 0, 0, 0.8);
    color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

/* Other element styles (omitted) */
  1. HTML structure: Create a basic HTML document structure, including the <head> section (introducing the CSS file) and the <body> section. Define a .container in the <body> as a container for the overall layout, which contains elements such as .header, .content (including .overlay-box child elements) and .footer.
  2. Basic CSS styles: Set common styles, such as fonts, page margins, etc. Here, position: relative is set for .container, which makes .container the positioning reference point for its internal absolutely positioned elements (such as .overlay-box).
  3. Absolutely positioned element style: Set position: absolute for .overlay-box to make it an absolutely positioned element. Then use top: 50% and left: 50% to position it relative to the center point of the nearest positioned ancestor (here is .container). Since the upper left corner of the element itself will be located at the center of the reference point after positioning, it is necessary to use transform: translate(-50%, -50%) to align the center of the element itself with the center of the reference point. Finally, set the width, padding, background color, text color, shadow and other styles.
  4. Other element styles: The style settings of other non-absolutely positioned elements (such as .header, .content and .footer) are omitted here. In actual projects, corresponding style settings need to be made according to needs.

CSS3 absolute layout uses the position: absolute attribute to separate elements from the document flow, and uses the top, right, bottom, left attributes or transform attributes to accurately control the position of elements. Absolute positioning is suitable for scenarios where elements need to be placed precisely at any position on the page, but it should be noted that it may affect the layout of other elements in the document flow. It is necessary to combine the z-index attribute to control the stacking order, and appropriately set the positioned ancestor elements to provide positioning references. In complex layouts and responsive designs, modern layout methods such as Flexbox or Grid layout may need to be combined to obtain better flexibility and control.

Table Layout

Table Layout refers to the use of HTML <table>, <tr>, <th>, <td> and other elements and related CSS attributes to organize data and content, simulating the traditional spreadsheet format to present information. Table layout can be used for actual data display, and can also be used as a layout tool to organize web page content.

<table>
    <caption>Product Sales Statistics</caption>
    <thead>
        <tr>
            <th>Product Name</th>
            <th>Sales Quantity</th>
            <th>Sales Amount (RMB)</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Product A</td>
            <td>100</td>
            <td>2500</td>
        </tr>
        <tr>
            <td>Product B</td>
            <td>150</td>
            <td>3750</td>
        </tr>
        <!-- More rows of data... -->
    </tbody>
</table>
  1. <table> element: represents the entire table, and all table-related elements are included in it.
  2. <caption> element: adds a title to the table and describes the main content of the table.
  3. <thead> element: contains the table header, usually contains <tr> (table row) and <th> (table header cell).
  4. <tr> element: defines a row of the table, which can contain <th> (table header cell) or <td> (data cell).
  5. <th> element: represents the table header cell, usually used to describe the meaning of the column data. By default, the <th> cell text is bold and centered.
  6. <tbody> element: contains the main content of the table, that is, the data row. Each row is defined by <tr>, and each cell is defined by <td>.
  7. <td> element: represents the data cell, which is used to store the actual data of the table.
  8. CSS style: CSS can be used to further beautify the table, such as setting borders, padding, background color, text alignment, etc. For

example:

table {
border-collapse: collapse; /* Merge table borders */
width: 100%; /* Specify table width */
}

th,
td {
border: 1px solid #ccc; /* Add cell borders */
padding: 8px; /* Set cell padding */
}

th {
background-color: #f2f2f2; /* Set table header background color */
text-align: left; /* Align text to the left */
}

Media responsive layout

@media media-type and (media-feature) {
/* Style rules to be applied when the conditions are met */
}
  • media-type: media type, such as screen, print, all, etc.
  • media-feature: media features, such as width (viewport width), height (viewport height), orientation (device orientation), etc. Common media

feature expressions are:

  • min-width / max-width: minimum/maximum viewport width.
  • min-height / max-height: minimum/maximum viewport height.
  • orientation: device orientation, the value is portrait (vertical screen) or landscape (horizontal screen).
  • device-width / device-height: device physical width/height (non-viewport).
  • resolution: device resolution, such as dpi (dots per inch), dpcm (dots per centimeter), etc.
/* Mobile and tablet */
@media only screen and (max-width: 767px) {
/* Styles for mobile and tablet devices */
}

/* Between tablet and desktop (including horizontal screen of tablet) */
@media only screen and (min-width: 768px) and (max-width: 1023px) {
/* Styles for tablet and smaller desktop display */
}

/* Normal desktop display */
@media only screen and (min-width: 1024px) and (max-width: 1280px) {
/* Styles for normal desktop display */
}

/* Widescreen desktop display */
@media only screen and (min-width: 1281px) and (max-width: 1439px) {
/* Styles for widescreen desktop display */
}

/* Ultra-widescreen display */
@media only screen and (min-width: 1440px) {
/* Style for ultra-wide screen displays */
}

Common media query sizes:

Mobile:

  • Small phones (e.g. iPhone SE, older Android devices): breakpoints are usually set between 320px and 480px.
  • Regular phones (e.g. iPhone 8/SE 2nd Gen, most modern Android phones): breakpoints are usually set between 375px and 414px (iPhone 8 width) or 360px and 420px (common Android phone width).

Tablets:

  • iPad mini, small tablets, and other similar devices: breakpoints are usually set around 768px, which is the standard width for small tablets like iPad mini.
  • iPad Pro, large tablets, and other similar devices: breakpoints may be set around 1024px, corresponding to the landscape width of larger tablets like iPad Pro.

Desktop monitors:

  • Regular desktop monitors: breakpoints are usually set between 1024px and 1280px, covering the width of most standard desktop monitors.
  • Widescreen desktop monitors: Breakpoints may be set at 1440px, 1920px, or even higher to accommodate widescreen monitors and high-resolution screens.

Ultrawide monitors:

  • Ultrawide: Breakpoints may be set at 2560px, 3440px, etc. to accommodate monitors with ultrawide ratios (such as 21:9).

Viewport units

Use the vw, vh, vmin, and vmax units to set element sizes based on the viewport size.

vw (viewport width):

1vw is equivalent to 1% of the viewport width.

For example, if you set an element’s width to 100vw, it will occupy the entire width of the viewport.

vh (viewport height):

1vh is equivalent to 1% of the viewport height.

If an element’s height is set to 50vh, it will occupy half the viewport height.

vmin:

1vmin is 1% of the smaller of vw and vh.

Use vmin when you want to size an element based on the smaller side of the viewport (either width or height).

vmax:

1vmax is 1% of the larger of vw and vh.

Using vmax makes an element size based on the wider side of the viewport, which is good for adapting to larger viewport sizes while maintaining proportions.

.header {
  height: 80vh; /* The height is 10% of the viewport height. */
}

.sidebar {
  width: 25vw; /* Width is 25% of the viewport width */
}

Flexible layout

display: flex

Turn on Flex layout mode. Set an element as a Flex container, and its direct children will become Flex items.

.container {
    display: flex;
}

flex-direction

Defines the main axis direction (the direction in which items are arranged). Optional values:

  • row (default): horizontal, from left to right.
  • row-reverse: horizontal, from right to left.
  • column: vertical, from top to bottom.
  • column-reverse: vertical, from bottom to top.
.container {
  flex-direction: row | row-reverse | column | column-reverse;
}

flex-wrap

Controls whether to wrap when there is not enough space in a line. Optional values:

  • nowrap (default): Do not wrap, items may overflow the container.
  • wrap: Wrap, items are arranged in multiple lines.
  • wrap-reverse: Wrap, the first line is at the bottom, and subsequent lines are arranged upwards.
.container {
  flex-wrap: nowrap | wrap | wrap-reverse;
}

justify-content

Defines the alignment on the main axis. Optional values:

  • flex-start (default): items are aligned to the start point.
  • flex-end: items are aligned to the end point.
  • center: items are aligned in the center.
  • space-between: items are evenly spaced, with the first and last items attached to the ends of the container.
  • space-around: items are evenly spaced, with equal spacing on both sides.
  • space-evenly: items are evenly spaced, with equal spacing between items and the container edge and between items.
.container {
  justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
}

align-items

Defines the alignment on the cross axis. Optional values:

  • stretch (default): items stretch to fill the entire cross axis.
  • flex-start: items align to the start of the cross axis.
  • flex-end: items align to the end of the cross axis.
  • center: items are centered on the cross axis.
  • baseline: items are aligned by the baseline.
.container {
  align-items: stretch | flex-start | flex-end | center | baseline;
}

align-content

Only works in multi-line flex layout (flex-wrap: wrap), defines the alignment of multi-line items on the cross axis. Optional values:

  • stretch (default): each row stretches to fill the entire cross axis.
  • flex-start: each row is aligned to the start of the cross axis.
  • flex-end: each row is aligned to the end of the cross axis.
  • center: each row is centered on the cross axis.
  • space-between: each row is evenly spaced, with the first and last rows attached to the ends of the container.
  • space-around: each row is evenly spaced, with equal spacing on both sides of the row.
.container {
  align-content: stretch | flex-start | flex-end | center | space-between | space-around;
}

order

Defines the order in which items are sorted. The smaller the value, the higher the item is sorted. The default value is 0.

.item {
  order: <integer>;
}

flex-grow

Defines the magnification ratio of the items. The default value is 0, which means no magnification. If all items are set to non-zero values, the remaining space is distributed proportionally.

.item {
  flex-grow: <number>; /* Default is 0 */
}

flex-shrink

Defines the scale of the item. The default value is 1, which means it can be scaled down. If all items are set to non-zero values, they shrink proportionally to prevent overflowing the container.

.item {
  flex-shrink: <number>; /* Default is 1 */
}

flex-basis

Defines the initial size of the item before the remaining space is distributed. Acceptable values ​​are length, percentage, auto (default), or content.

.item {
  flex-basis: <length> | <percentage> | auto | content;
}

flex

Shorthand for flex-grow, flex-shrink, and flex-basis. Default value is 0 1 auto.

.item {
  flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ];
}

align-self

Overrides the container’s align-items property to define the alignment of individual items on the cross axis. The optional values ​​are the same as align-items.

.item {
  align-self: auto | stretch | flex-start | flex-end | center | baseline;
}

Grid layout

display: grid;

Turn on Grid layout mode. Set an element as a Grid container, and its direct child elements will become Grid items (cells).

.container {
  display: grid;
}

grid-template-columns and grid-template-rows

Defines the size of the grid’s column and row tracks. Accepts length, percentage, fr (fraction unit, representing the fraction of the grid space), or auto values. You can also create repeating tracks with the repeat() function, and define the minimum and maximum size of a track with the minmax() function.

.container {
  grid-template-columns: <track-size> ... | repeat(<number>, <track-size>) | auto-fill | auto-fit;
  grid-template-rows: <track-size> ... | repeat(<number>, <track-size>) | auto-fill | auto-fit;
}

/* Example */
.container {
    grid-template-columns: 1fr 2fr 1fr; /* Three columns, width ratio is 1:2:1 */
    grid-template-rows: 50px auto 1fr; /* Three rows, the first row is 50px, the second row is adaptive height, and the third row is the remaining space */
}

grid-template-areas

Define the areas of the grid layout by naming the items and describing the grid structure with strings. The item names use . to represent blank cells.

.container {
  grid-template-areas:
    "header header header"
    "nav main sidebar"
    "footer footer footer";
}

/* The corresponding project needs to set the grid-area attribute */
.item1 {
  grid-area: header;
}
.item2 {
  grid-area: nav;
}
.item3 {
  grid-area: main;
}
.item4 {
  grid-area: sidebar;
}
.item5 {
  grid-area: footer;
}

grid-gap or grid-column-gap and grid-row-gap

Sets the gap between items in the grid. Accepts length or percentage value.

.container {
    grid-gap: <grid-row-gap> <grid-column-gap>; /* Shorthand form, set row and column spacing at the same time */
    grid-row-gap: <length> | <percentage>; /* Set row spacing separately */
    grid-column-gap: <length> | <percentage>; /* Set column spacing separately */
}

/* Example */
.container {
  grid-gap: 10px 20px; /* 10px row spacing, 20px column spacing */
}

grid-auto-columns and grid-auto-rows

Defines the size of the track for newly added rows or columns when automatically filling the grid. Takes effect when the item exceeds the defined grid range.

.container {
  grid-auto-columns: <track-size> ... | repeat(<number>, <track-size>);
  grid-auto-rows: <track-size> ... | repeat(<number>, <track-size>);
}

/* Example */
.container {
  grid-auto-rows: minmax(100px, auto); /* The minimum height of a newly added row is 100px, and the maximum height is adaptive to the content */
}

grid-auto-flow

Controls how grid items are automatically filled and arranged. Possible values:

  • row (default): fill by row.
  • column: fill by column.
  • dense: When row or column is used with dense, if there are gaps in the grid, new items will try to fill those gaps instead of just being added to the end of the grid.
.container {
  grid-auto-flow: row | column | row dense | column dense;
}

grid-column-start、grid-column-end、grid-row-start 和 grid-row-end

Manually specify the starting and ending positions of items in the grid.

.item {
  grid-column-start: <line-number> | <name> | auto;
  grid-column-end: <line-number> | <name> | span <number> | auto;
  grid-row-start: <line-number> | <name> | auto;
  grid-row-end: <line-number> | <name> | span <number> | auto;
}

/* Example */
.item {
    grid-column: 1 / 3; /* Equivalent to grid-column-start: 1; grid-column-end: 3;, occupying the first to third columns */
    grid-row: 2 / span 2; /* Equivalent to grid-row-start: 2; grid-row-end: span 2;, starting from the second row, spanning two rows */
}

grid-area

Shorthand property for setting grid-row-start, grid-column-start, grid-row-end, and grid-column-end at the same time, or referencing an area name defined in grid-template-areas.

.item {
  grid-area: <name> | <row-start> / <column-start> / <row-end> / <column-end>;
}

/* Example */
.item {
  grid-area: header; /* Refer to the area name defined in grid-template-areas */
}

Multi-column layout

columns

Shorthand property for setting column-count and column-width at the same time.

.container {
  columns: <column-width> || <column-count>;
}

/* Example */
.container {
    columns: ⅓; /* equivalent to column-count: 3; column-width: auto; */
    columns: 200px 3; /* equivalent to column-count: 3; column-width: 200px; */
}

column-count

Defines the number of columns the container should be split into. Accepts non-negative integer values.

.container {
  column-count: <integer>;
}

/* Example */
.container {
    column-count: 3; /* Divide the content into three columns */
}

column-width

Specifies the desired minimum width for each column. Accepts a length value. If the container is not wide enough to accommodate the specified number of columns, the number of columns will be reduced.

.container {
  column-width: <length>;
}

/* Example */
.container {
  column-width: 300px; /* Each column is at least 300px wide */
}

column-gap

Sets the amount of space between columns. Accepts a length value.

.container {
  column-gap: <length>;
}

/* Example */
.container {
  column-gap: 2em; /* The spacing between columns is 2em */
}

column-rule

Defines the style, width, and color of the column dividers, similar to border properties. You can set column-rule-width, column-rule-style, and column-rule-color separately, or use the shorthand property to set them all at once.

.container {
  column-rule: <column-rule-width> || <column-rule-style> || <column-rule-color>;
}

/* Example */
.container {
  column-rule: 1px solid #ccc; /* The width of the separator line is 1px, solid line, and the color is light gray. */
}

break-inside

Controls whether items (usually paragraphs or other block-level elements) should avoid breaking between columns. Possible values:

  • auto (default): The browser decides whether to break.
  • avoid: Avoid items breaking between columns when possible.
.item {
    break-inside: auto | avoid;
}

/* Example */
.paragraph {
    break-inside: avoid; /* Prevent paragraphs from breaking between columns */
}

Global properties:

  • break-before and break-after
  • Controls whether column breaks should be inserted before or after items. Possible values:
  • auto (default): The browser decides whether to insert a breakpoint.
  • always: Always insert a breakpoint before/after an item.
  • avoid: Avoid inserting a breakpoint before/after an item when possible.
  • avoid-column: Avoid inserting a column breakpoint before/after an item.
  • avoid-page: Avoid inserting a page breakpoint before/after an item.
  • column: Force column breakpoints before/after an item.
  • left / right / recto / verso: Breakpoint controls related to page direction.
.item {
  break-before: auto | always | avoid | avoid-column | avoid-page | column | left | right | recto | verso;
  break-after: auto | always | avoid | avoid-column | avoid-page | column | left | right | recto | verso;
}

/* Example */
.section-header {
  break-before: column; /* Force a column break before the title */
}
Share your love