Comprehensive Guide to CSS Styling and Layout
Inclusion Methods
Direct Attribute Styling
Styles applied directly to an element via the style attribute. This approach lacks reusability and prevents separation of structure and presentation.
<section style="outline: 2px dashed blue; background: lightgreen; width: 150px; height: 150px;">Inline styled element</section>Document-Level Styling
Defined within a <style> block in the HTML document, typically placed in the <head> section to ensure early rendering.
<style>
section {
outline: 2px dashed blue;
background: lightcoral;
width: 150px;
height: 150px;
}
</style>Linked External Resources
Using the <link> tag or @import rule to attach an external stylesheet. The <link> method is preferred for parallel loading and better performance.
<link rel="stylesheet" href="styles/main.css"><style>@import url("styles/main.css");</style>Selectors
Basic Selectors
Selectors bind to elements for styling. Formats include:
- Element Selector: Targets the tag name directly (e.g.,
div). - Class Selector: Uses a dot prefix (e.g.,
.card). Core to component-based architecture. Elements can hold multiple classes separated by spaces. - ID Selector: Uses a hash prefix (e.g.,
#nav-bar). Must be unique within a document. - Universal Selector: Denoted by
*, targets all elements. Commonly used for resetting margins:* { margin: 0; }.
Relational Selectors
- Direct Child:
parent > child- Selects immediate children only. - Descendant:
ancestor descendant- Selects all nested descendants across multiple levels. - Adjacent Sibling:
el + sibling- Selects the next immediate sibling. - General Sibling:
el ~ siblings- Selects all subsequent siblings.
Attribute Selectors
Target elements based on their attributes:
[attr]- Has the attribute.[attr="val"]- Exact match.[attr^="val"]- Starts with.[attr$="val"]- Ends with.[attr*="val"]- Contains substring.
<style>
[data-type] { font-size: 2rem; }
[data-type="primary"] { background: whitesmoke; }
</style>
<p data-type="primary">Attribute targeted</p>Composite Selectors
- Intersection: Chaining selectors without spaces (e.g.,
div.active). Matches elements fulfilling all conditions. - Union: Comma-separated selectors (e.g.,
h1, h2). Targets all matching elements.
Pseudo-classes
Target an element's state or structural position using a single colon :.
Link States
Must follow the LVHA order: :link, :visited, :hover, :active.
Form States
:focus- Element receives focus.:not(selector)- Excludes matching elements.:required- Mandatory input fields.:checked- Selected checkboxes or radio buttons.
Structural States
:first-child- First child of its parent.:first-of-type- First child of its specific element type.:last-child- Last child.:nth-child(n)- Nth child (accepts numbers,odd,even).
Pseudo-elements
Create or style virtual elements using a double colon ::.
::first-letter- Styles the initial character.::first-line- Styles the first rendered line.::selection- Styles user-selected text.::before/::after- Inserts generated content before or after the element, requiring thecontentproperty.
Visual Styles
Backgrounds
Properties include background-color, background-image, background-repeat, background-attachment, background-position, and background-size. The shorthand background combines these.
background: url("bg.png") center/cover no-repeat fixed;Typography
Control text appearance through color, font-size, font-style, font-weight, font-family, line-height, text-decoration, text-indent, text-align, text-transform, and text-shadow.
Lists
Modify list markers using list-style-type, list-style-image, and list-style-position.
Box Model
Comprises content, padding, border, and margin.
- Padding: Space between content and border. Shorthand follows top, right, bottom, left order.
- Border:
border: 2px solid gray;. Useborder-radiusfor rounded corners andbox-shadowfor depth. - Margin: Space outside the border.
margin: autocenters block elements horizontally.
Setting box-sizing: border-box shifts to the alternative box model, where width and height include padding and border, preventing layout overflow when adding spacing.
Display Modes
Convert element behaviors using the display property:
block- Makes inline elements behave as blocks.inline- Makes block elements flow inline.inline-block- Allows inline flow while retaining block dimensions.
Float
The float property pulls elements out of the normal document flow, originally intended for text wrapping, but historically used for layout structures.
Positioning
static- Default, normal flow.relative- Offset from its normal position.absolute- Positioned relative to the nearest positioned ancestor; otherwise, relative to the viewport.fixed- Anchored to the viewport, ignoring scroll.
Advanced Styling
Media Queries
Apply styles conditionally based on device types (screen, print, all) and viewport dimensions.
@media print { .nav { display: none; } }
@media only screen and (min-width: 900px) { .sidebar { width: 300px; } }
@media only screen and (max-width: 400px) { .grid { flex-direction: column; } }Custom Fonts
Define and load custom typefaces using @font-face.
@font-face {
font-family: "CustomSerif";
src: url("fonts/serif-bold.woff2");
}
p { font-family: "CustomSerif"; }Transitions
Animate state changes smoothly. Requires a trigger (e.g., :hover), properties to animate, and a duration.
.panel {
width: 150px;
transition: width 0.4s ease-in-out 0.1s;
}
.panel:hover { width: 300px; }Timing functions include linear, ease, ease-in, ease-out, and ease-in-out.
Transforms
Modify element geometry without affecting surrounding layout.
translate(x, y)- Moves the element.rotate(deg)- Spins the element.scale(x, y)- Resizes the element.skew(xdeg, ydeg)- Distorts the element along axes.
Animations
Define keyframes for complex, repeating sequences.
@keyframes expand {
from { width: 50px; }
to { width: 200px; }
}
.loader {
animation-name: expand;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
}Gradients
Create smooth color transitions as background images.
- Linear:
linear-gradient(direction, color1, color2). Direction can be keywords (to right) or angles (90deg). - Radial:
radial-gradient(shape size at position, start-color, last-color). - Repeating:
repeating-linear-gradient(...)for patterned backgrounds.
Transparency is achievable using rgba() color stops.
Multi-Column Layout
Segment text into newspaper-style columns.
column-count- Number of columns.column-width- Minimum column width.column-gap- Space between columns.column-rule- Border styling between columns.column-span: all- Allows an element to span all columns.
Layout Strategies
Float-Based Layout
Traditional approach using floated div elements to construct grid-like structures (e.g., an "I-beam" layout with header, multi-column body, and footer).
.header, .footer { height: 80px; background: lightblue; }
.body-wrap > .sidebar { float: left; width: 20%; }
.body-wrap > .main { float: left; width: 60%; }Table Layout
Using HTML table elements (<table>, <tr>, <td>) for page structure. Requires rowspan and colspan for merging cells, but is generally discouraged for modern layouts.
Flexbox Layout
A two-dimensional alignment system for distributing space along a main axis and a cross axis.
.flex-wrap {
display: flex;
flex-flow: row wrap;
justify-content: space-between; /* Main axis alignment */
align-items: center; /* Cross axis alignment */
}
.flex-item {
flex: 1 1 200px; /* grow | shrink | basis */
align-self: flex-start; /* Individual cross axis override */
}Grid Layout
A robust two-dimensional system for complex layouts.
.grid-wrap {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 150px);
}
.grid-child-1 {
grid-column: 1 / 4; /* Spans all 3 columns */
}
.grid-child-2 {
grid-area: 2 / 2 / 3 / 3; /* row-start / col-start / row-end / col-end */
}