CSS Intermediate

CSS Layout with Display and Position

CodingerWeb
CodingerWeb
18 views 55 min read

Understanding CSS Display Property

The display property is fundamental to CSS layout, controlling how elements are rendered and how they interact with other elements.

Display Values

Block Elements

display: block;
/* Takes full width, starts on new line */
/* Examples: div, h1-h6, p, section */

Inline Elements

display: inline;
/* Takes only necessary width, stays on same line */
/* Examples: span, a, strong, em */

Inline-Block

display: inline-block;
/* Combines inline and block behavior */
/* Stays on same line but accepts width/height */

None

display: none;
/* Completely removes element from layout */

CSS Position Property

Static (Default)

position: static;
/* Normal document flow */
/* top, right, bottom, left have no effect */

Relative

position: relative;
top: 10px;
left: 20px;
/* Positioned relative to its normal position */

Absolute

position: absolute;
top: 50px;
right: 30px;
/* Positioned relative to nearest positioned ancestor */

Fixed

position: fixed;
top: 0;
left: 0;
/* Positioned relative to viewport */
/* Stays in place when scrolling */

Sticky

position: sticky;
top: 0;
/* Switches between relative and fixed */
/* Based on scroll position */

Z-Index

z-index: 10;
/* Controls stacking order */
/* Higher values appear on top */
/* Only works on positioned elements */

Practical Layout Example

<style>
.container {
    position: relative;
    width: 100%;
    height: 400px;
    background-color: #f8f9fa;
    border: 2px solid #dee2e6;
}

.header {
    position: sticky;
    top: 0;
    background-color: #007bff;
    color: white;
    padding: 1rem;
    z-index: 100;
}

.sidebar {
    position: absolute;
    top: 60px;
    left: 0;
    width: 200px;
    height: calc(100% - 60px);
    background-color: #e9ecef;
    padding: 1rem;
}

.main-content {
    margin-left: 220px;
    padding: 1rem;
}

.floating-button {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background-color: #28a745;
    color: white;
    border: none;
    border-radius: 50%;
    width: 60px;
    height: 60px;
    z-index: 1000;
}

.inline-elements span {
    display: inline-block;
    background-color: #ffc107;
    padding: 0.5rem;
    margin: 0.25rem;
    border-radius: 4px;
}
</style>

<div class="container">
    <div class="header">Sticky Header</div>
    <div class="sidebar">Sidebar Content</div>
    <div class="main-content">
        <h2>Main Content</h2>
        <div class="inline-elements">
            <span>Tag 1</span>
            <span>Tag 2</span>
            <span>Tag 3</span>
        </div>
    </div>
    <button class="floating-button">+</button>
</div>