banner
cos

cos

愿热情永存,愿热爱不灭,愿生活无憾
github
tg_channel
bilibili

Youth Training Camp | "CSS Layout"

Layout#

When laying out a document, the browser's rendering engine represents all elements as rectangular boxes according to one of the standards, the CSS Basic Box Model. CSS determines the size, position, and properties (such as color, background, border size, etc.) of these boxes.
Each box consists of four parts (or areas), whose utility is defined by their respective edges. As shown in the figure, corresponding to the four components of the box, each box has four boundaries: Content Edge, Padding Edge, Border Edge, and Margin Edge.

width#

Specifies the width of the content box, which can be a length, percentage, auto, etc. The percentage is relative to the width of the content box.

height#

Specifies the height of the content box, which can be a length, percentage, auto, etc. The percentage is relative to the height of the content box. Both width and height need to be noted that if using percentages, the content box must specify width/height; otherwise, it will not take effect.

padding#

Specifies the padding on all four sides. Its percentage is relative to the container width; see padding - CSS | MDN (mozilla.org)

  • When only one value is specified, that value will be uniformly applied to the padding of all four sides.
  • When two values are specified, the first value will apply to the top and bottom padding, and the second value applies to the left and right.
  • When three values are specified, the first value applies to the top, the second value applies to the right and left, and the third applies to the bottom padding.
  • When four values are specified, they are applied in order (clockwise) as top, right, bottom, and left padding.
    image.png

margin#

Specifies the margin on all four sides. Its percentage is relative to the container width; see margin - CSS | MDN (mozilla.org)

  • When only one value is specified, that value will be uniformly applied to the margin of all four sides.
  • When two values are specified, the first value will apply to the top and bottom margin, and the second value applies to the left and right.
  • When three values are specified, the first value applies to the top, the second value applies to the right and left, and the third applies to the bottom margin.
  • When four values are specified, they are applied in order (clockwise) as top, right, bottom, and left margin.
    Margin collapse: Margin Collapsing - CSS | MDN (mozilla.org). The margins of two adjacent elements overlap, causing margin collapse in the vertical direction, retaining the maximum margin range.

border#

Specifies the border, where border-width specifies the width, border-style specifies the type (solid/dashed), and border-color specifies the border color. Usually, all three are combined and abbreviated as border; see border - CSS | MDN (mozilla.org)

  • Clever use of border: creating triangles
    • First, set different colors for the four borders. You can see that the corners are cut by diagonal lines.
      image.png
    • When the container's height and width are 0, it looks like this.
      image.png
    • If the other border colors are set to transparent, a red triangle can be created.
      image.png

box-sizing#

box-sizing - CSS | MDN (mozilla.org)

In the default definition of the CSS Box Model, the width and height set for an element only apply to the content area of that element. If the element has any border or padding, the width and height of the box drawn on the screen will include the set border and padding values. This means that when you adjust an element's width and height, you need to always be aware of that element's border and padding. This characteristic is particularly annoying when we implement responsive layouts.

The box-sizing property can be used to adjust these behaviors:

  • content-box is the default value. If you set an element's width to 100px, then the content area of that element will be 100px wide, and any border and padding width will be added to the final rendered width of the element.
  • border-box tells the browser that the values for border and padding you want to set are included in the width. That is, if you set an element's width to 100px, then this 100px will include its border and padding, and the actual width of the content area is the width minus the values of (border + padding). In most cases, this makes it easier for us to set an element's width and height.

overflow#

overflow - CSS | MDN (mozilla.org)

The CSS property overflow defines what should happen when an element's content is too large to fit in the block formatting context. It is a shorthand property for overflow-x and overflow-y.

Setting it to auto will display a scrollbar when the content is too much; otherwise, it will not display. For overflow to take effect, the block-level container must have a specified height (height or max-height) or set white-space to nowrap.

Block-level elements#

Block-level elements - HTML | MDN (mozilla.org)

Block-level elements occupy the entire horizontal space of their parent element (container), and the vertical space equals their content height. Typically, browsers will start a new line before and after block-level elements.

  • Common examples include body, article, div, main, section, h1-h6, p, ul, li
  • display: block

Inline elements#

Inline elements - HTML | MDN (mozilla.org)

An inline element only occupies the space contained within the borders of its corresponding tag.
Inline elements do not use the width and height properties from the box model.

  • Common examples include span, em, strong, cite, section, code, etc.

  • display: inline

Speaking of the display property, its description can be found at display - CSS | MDN (mozilla.org):

The display property can set the internal and external display types of an element. The external display types will determine how the element behaves in flow layout (block-level or inline elements); the internal display types can control the layout of its child elements (for example: flow layout, grid, or flex).

  • block block-level box
  • inline inline box
  • inline-block is inline itself, can be placed in inline boxes, can set width and height, and as a whole will not be broken into multiple lines.
  • none completely ignored during layout

Normal Flow#

  • The root element, floating, and absolutely positioned elements will be removed from the normal flow, while other elements remain in the normal flow (in-flow). Boxes in the normal flow participate in layout within a certain formatting context.
  • Inline formatting context, block formatting context, table formatting context, flex formatting context, grid formatting context...

Inline Formatting Context (IFC)#

Inline Formatting Context - CSS | MDN

The inline formatting context is part of the rendering result of a web page. In this context, inline boxes are arranged one after another, with their order determined by the writing mode settings:

  • For horizontal writing mode, the boxes are arranged horizontally from the left.
  • For vertical writing mode, the boxes are arranged horizontally from the top.

In the example below, the two elements with black borders (<div>) form a block formatting context, where each word participates in an inline formatting context. In horizontal writing mode, the boxes are arranged horizontally, and in vertical writing mode, the boxes are arranged vertically.

  • A container that only contains inline boxes will create an IFC, with the following typographic rules:

    • Boxes are laid out horizontally in a line, and when a line cannot fit, they will wrap to the next line.
    • text-align determines the horizontal alignment of boxes within a line.
    • vertical-align determines the vertical alignment of a box within a line.
    • Avoid floating elements.
  • A paragraph is actually a collection of line boxes arranged in the block direction.

  • When an inline box is split across multiple lines, the settings for margins, borders, and padding will not take effect at the break point. In the example below, there is a (<span>) element that wraps a series of words and occupies two lines. You can see that at the break point, the <span> border also breaks.

image.png

Block Formatting Context (BFC)#

Block Formatting Context | MDN

  • Block Formatting Context (BFC)
  • Boxes are placed from top to bottom.
  • Vertical margins within a BFC will merge (see margin collapse in the previous section).
  • Margins of boxes within a BFC will not merge with those outside.
  • BFC will not overlap with floating elements.

FlexBox#

Basic Concepts of Flex Layout | MDN

  • A new formatting context

  • Can control the child boxes':

    • Flow direction (flex-direction)
      • Default (row): from left to right →
      • row-reverse: from right to left ←
      • column: from top to bottom ↓
      • column-reverse: from bottom to top ↑
    • Order of placement
    • Box height and width
    • Horizontal and vertical alignment (strictly speaking, alignment along the main axis and cross axis, see justify-content and align-items)
    • Whether to allow wrapping (wrap, nowrap, wrap-reverse)
    • Other properties on flex items (flex properties such as flex-grow, flex-shrink, flex-basis)
  • Flex items will create a BFC.

Let’s emphasize the alignment along the main axis and cross axis. With the default arrangement from left to right (row), the main axis is horizontal, and the cross axis is vertical. The alignment methods along the main axis (justify-content) are as follows (initial value is flex-start):

  • flex-start aligns at the start of the main axis
  • flex-end aligns at the end of the main axis
  • center aligns in the center of the main axis
  • space-between aligns at both ends of the main axis, with space in between
  • space-around adds space on both sides of the main axis, keeping the element size unchanged
  • space-evenly makes the space on both sides equal to the space in the middle
    image.png

The alignment methods along the cross axis are as follows (initial value is stretch):

  • flex-start: aligns at the start of the cross axis
  • flex-end: aligns at the end of the cross axis
  • center: aligns in the center of the cross axis
  • stretch: stretches the element to fit the container along the cross axis
  • baseline: aligns based on the baseline
  • image.png

If you want to give a specific element in flex special treatment, you can set an align-self property for it, as shown in the image.

image.png

order can set the order of elements during layout.

image.png

So how will the content in the flex container change when the webpage is stretched or shrunk?

  • You can control the stretching ability when there is remaining space by setting flex-grow, and control the shrinking when there is insufficient remaining space by setting flex-shrink.

  • The flex-grow property can allocate space proportionally. If the first element's flex-grow value is 2, and the other elements' values are 1, then the first element will occupy 2/4, while the other two elements will each occupy 1/4.

  • The flex-shrink property works similarly to flex-grow, allowing you to assign different values to control the degree of shrinkage of flex elements—assigning a larger value to flex-shrink will allow it to shrink more than elements with smaller values.

  • The flex-basis property defines the base length when not stretching or shrinking.

Regarding flex layout, I previously saw a demo project on codepen that illustrates the effect of each property, highly recommended to try it out yourself: Flexbox playground (codepen.io)

image.png

Grid Layout#

Grid - Glossary | MDN (mozilla.org)

  • display: grid will create a block-level Grid container for the element.

  • You can use grid-template related properties to divide the container into a grid.

    • grid-template-rows defines the names of grid lines and the sizes of grid tracks based on grid rows.
    • grid-template-columns defines the names of grid lines and the sizes of grid tracks based on grid columns.
    • You can define minmax(min, max), which is a property to define a size range, being greater than or equal to min and less than or equal to max. If the max value is less than the min value, it will be treated as the min value. The maximum value can be set as a grid track coefficient value fr, but the minimum value cannot.
    • You can also use the unit fr to define the elastic coefficient of the above grid track sizes. Each grid track defined with fr will proportionally allocate the remaining available space. When the outer layer is represented with a minmax(), it will be an automatic minimum value (i.e., minmax(auto, <flex>)).
    • Want an element to span multiple rows/columns?
      • grid line
      • grid area
      • Use grid-template-columns-start/grid-template-columns-end, etc., which can be abbreviated as grid-area;

Following a small demo written in class: Grid (codepen.io), which is also an intuitive example.

  • First, set the container as a grid with 4 rows and 2 columns.
#container {
  width: 300px;
  height: 500px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr 1fr;
}

image.png

  • Then set element A to start from the first grid row line to the third grid row line, occupying two rows, and similarly occupying two columns, as shown.
.a {
  grid-row-start: 1;
  grid-column-start: 1;
  grid-row-end: 3;
  grid-column-end: 3;
}

This can be abbreviated as:

.a {
  grid-area:1/1/3/3;
}

As shown, A occupies two rows and two columns.
image.png

  • Then make some changes, changing a to span rows/columns 2-4, occupying the 2nd and 3rd rows/columns, and changing b to span rows/columns 1-3, occupying the 1st and 2nd rows/columns.
.a {
  grid-area:2/2/4/4;
}
.b {
  grid-area:1/1/3/3;
}

image.png

Float#

In the past, text wrapping around images was achieved using float; now it is just for understanding. For details, see float - CSS | MDN (mozilla.org).

  • Float allows text and inline elements to wrap around it. An element with the float property is removed from the normal flow of the webpage (document flow).

  • Once an element floats, it is removed from the normal document flow and shifts left or right until it hits the border of its container or another floating element.

  • Note that if you want the following elements to be forced below any floating elements after using float, you must use the clear property.

Positioning#

The position property is used to specify how an element is positioned in the document. The top, right, bottom, and left properties determine the final position of the element.

Position has the following types:

  • static: default value, non-positioned element
  • relative: offset relative to its original position, does not leave the document flow
  • absolute: absolutely positioned, relative to the nearest non-static ancestor
  • fixed: absolutely positioned relative to the viewport

Relative Positioning (relative)#

position

  • Layouts in the normal flow
  • Offsets relative to where it should be (top, left, bottom, right)
  • Other elements in the flow layout as if it has not been offset

Absolute Positioning (absolute)#

position

  • Removed from the normal flow
  • Positioned relative to the nearest non-static ancestor
    • For example, to create a badge for an icon, set the icon to position, and then set its position to absolute for offsetting.
  • Will not affect the layout of elements in the flow

Suggestions and Thoughts#

  • Make full use of MDN and World Wide Web Consortium (W3C) CSS specifications
  • Maintain curiosity and make good use of browser developer tools
  • Keep learning, as new CSS features are continuously emerging

This can also be considered as a 整理 of my CSS learning. Regarding the above layouts, the main thing is to practice more, check more, and grow through practice. The more you use it, the more naturally you will remember it. Also, when you see interesting frontend projects, you should study them to see how excellent projects are laid out.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.