or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ajax.mdcore-selection.mdcss-styling.mddeferred-promises.mdeffects.mdevents.mdindex.mdmanipulation.mdutilities.md
tile.json

css-styling.mddocs/

CSS and Styling Operations

jQuery provides comprehensive methods for manipulating CSS properties, dimensions, positioning, and visual styles with full TypeScript support. These methods handle cross-browser compatibility and provide convenient abstractions for complex styling operations.

CSS Property Manipulation

Core CSS Methods

interface JQuery<TElement = HTMLElement> {
    // Get/set CSS properties
    css(propertyName: string): string;
    css(propertyNames: string[]): JQuery.PlainObject<string>;
    css(propertyName: string, value: string | number | ((this: TElement, index: number, value: string) => string | number)): this;
    css(properties: JQuery.PlainObject<string | number | ((this: TElement, index: number, value: string) => string | number)>): this;
}

CSS Property Examples

// Get single CSS property
const color = $('#element').css('color');
const fontSize = $('#element').css('font-size');
const backgroundColor = $('#element').css('background-color');

// Get multiple CSS properties
const styles = $('#element').css(['color', 'font-size', 'margin']);
console.log(styles); // { color: 'rgb(0, 0, 0)', 'font-size': '16px', margin: '10px' }

// Set single CSS property
$('#element').css('color', 'red');
$('#element').css('font-size', '18px');
$('#element').css('background-color', '#f0f0f0');

// Set CSS property with number (px added automatically)
$('#element').css('width', 200);        // Sets to '200px'
$('#element').css('height', 150);       // Sets to '150px'
$('#element').css('margin-top', 10);    // Sets to '10px'

// Set multiple CSS properties
$('#element').css({
    'color': 'blue',
    'font-size': '20px',
    'background-color': '#ffffff',
    'border': '1px solid #ccc',
    'border-radius': '5px',
    'padding': '10px'
});

// Function-based property setting
$('.items').css('background-color', function(index) {
    return index % 2 === 0 ? '#f9f9f9' : '#ffffff';
});

// Dynamic property calculation
$('.boxes').css('width', function(index, currentWidth) {
    const numericWidth = parseInt(currentWidth, 10);
    return (numericWidth + (index * 10)) + 'px';
});

Dimensions and Sizing

Dimension Methods

interface JQuery<TElement = HTMLElement> {
    // Width methods
    width(): number | undefined;
    width(value: number | string | ((this: TElement, index: number, width: number) => number | string)): this;
    
    // Height methods  
    height(): number | undefined;
    height(value: number | string | ((this: TElement, index: number, height: number) => number | string)): this;
    
    // Inner dimensions (including padding)
    innerWidth(): number | undefined;
    innerWidth(value: number | string | ((this: TElement, index: number, width: number) => number | string)): this;
    innerHeight(): number | undefined;
    innerHeight(value: number | string | ((this: TElement, index: number, height: number) => number | string)): this;
    
    // Outer dimensions (including padding and border)
    outerWidth(includeMargin?: boolean): number | undefined;
    outerWidth(value: number | string | ((this: TElement, index: number, width: number) => number | string)): this;
    outerHeight(includeMargin?: boolean): number | undefined;
    outerHeight(value: number | string | ((this: TElement, index: number, height: number) => number | string)): this;
}

Dimension Examples

// Get dimensions
const width = $('#element').width();        // Content width
const height = $('#element').height();      // Content height
const innerW = $('#element').innerWidth();  // Content + padding
const innerH = $('#element').innerHeight(); // Content + padding
const outerW = $('#element').outerWidth();  // Content + padding + border
const outerH = $('#element').outerHeight(); // Content + padding + border
const fullW = $('#element').outerWidth(true);  // Including margin
const fullH = $('#element').outerHeight(true); // Including margin

console.log(`Element dimensions:
  Content: ${width}x${height}
  Inner: ${innerW}x${innerH}  
  Outer: ${outerW}x${outerH}
  Full: ${fullW}x${fullH}`);

// Set dimensions
$('#element').width(300);
$('#element').height(200);
$('#element').innerWidth(350);   // Sets content width accounting for padding
$('#element').innerHeight(250);  // Sets content height accounting for padding

// Function-based sizing
$('.responsive-boxes').width(function(index) {
    return 100 + (index * 50); // Increasing widths: 100px, 150px, 200px...
});

$('.equal-height').height(function() {
    return $(this).siblings().height(); // Match sibling height
});

// Responsive sizing based on container
$('.child-elements').each(function() {
    const $parent = $(this).parent();
    const parentWidth = $parent.width()!;
    $(this).width(parentWidth * 0.8); // 80% of parent width
});

Positioning and Coordinates

Position Methods

interface JQuery<TElement = HTMLElement> {
    // Get/set position relative to offset parent
    position(): JQuery.Coordinates;
    
    // Get/set offset from document
    offset(): JQuery.Coordinates | undefined;
    offset(coordinates: JQuery.CoordinatesPartial): this;
    offset(func: (this: TElement, index: number, coords: JQuery.Coordinates) => JQuery.CoordinatesPartial): this;
    
    // Scroll position
    scrollTop(): number | undefined;
    scrollTop(value: number): this;
    scrollLeft(): number | undefined;
    scrollLeft(value: number): this;
}

declare namespace JQuery {
    interface Coordinates {
        left: number;
        top: number;
    }
    
    interface CoordinatesPartial {
        left?: number;
        top?: number;
    }
}

Position Examples

// Get position information
const position = $('#element').position();  // Relative to offset parent
const offset = $('#element').offset();      // Relative to document
const scrollTop = $('#element').scrollTop();
const scrollLeft = $('#element').scrollLeft();

console.log(`Position: ${position.left}, ${position.top}`);
console.log(`Offset: ${offset?.left}, ${offset?.top}`);
console.log(`Scroll: ${scrollLeft}, ${scrollTop}`);

// Set offset position
$('#element').offset({ top: 100, left: 150 });

// Function-based positioning
$('.draggable').offset(function(index, currentOffset) {
    return {
        top: currentOffset.top + 10,
        left: currentOffset.left + (index * 20)
    };
});

// Center element in viewport
function centerElement($element: JQuery) {
    const $window = $(window);
    const elementWidth = $element.outerWidth()!;
    const elementHeight = $element.outerHeight()!;
    const windowWidth = $window.width()!;
    const windowHeight = $window.height()!;
    
    $element.offset({
        left: (windowWidth - elementWidth) / 2,
        top: (windowHeight - elementHeight) / 2 + $window.scrollTop()!
    });
}

centerElement($('#modal'));

// Scroll to element
function scrollToElement($element: JQuery, duration = 500) {
    const targetOffset = $element.offset()!;
    $('html, body').animate({
        scrollTop: targetOffset.top - 50  // 50px offset from top
    }, duration);
}

scrollToElement($('#target-section'));

// Set scroll position
$('#scrollable-container').scrollTop(200);
$('#horizontal-scroll').scrollLeft(300);

// Smooth scroll with animation
$('#container').animate({
    scrollTop: 500
}, 1000);

Visual State and Display

Visibility Methods

interface JQuery<TElement = HTMLElement> {
    // Check visibility states
    is(selector: ":visible"): boolean;
    is(selector: ":hidden"): boolean;
}

// jQuery extensions for visibility
declare global {
    interface JQuery {
        // Check if element is in viewport
        isInViewport(): boolean;
    }
}

// Custom visibility extensions
$.fn.isInViewport = function() {
    if (this.length === 0) return false;
    
    const elementTop = this.offset()!.top;
    const elementBottom = elementTop + this.outerHeight()!;
    const viewportTop = $(window).scrollTop()!;
    const viewportBottom = viewportTop + $(window).height()!;
    
    return elementBottom > viewportTop && elementTop < viewportBottom;
};

Visibility Examples

// Check visibility
const isVisible = $('#element').is(':visible');
const isHidden = $('#element').is(':hidden');

console.log(`Element visible: ${isVisible}, hidden: ${isHidden}`);

// Show/hide with different methods
$('#element').show();        // display: block/inline/etc
$('#element').hide();        // display: none
$('#element').toggle();      // Toggle between show/hide

// CSS visibility vs display
$('#element').css('visibility', 'hidden');  // Hidden but takes space
$('#element').css('visibility', 'visible'); // Visible again
$('#element').css('display', 'none');       // Hidden, no space
$('#element').css('display', 'block');      // Visible, takes space

// Conditional visibility
$('.conditional').each(function() {
    const shouldShow = $(this).data('condition');
    $(this).toggle(shouldShow);
});

// Fade visibility
$('#element').fadeIn(500);
$('#element').fadeOut(500);
$('#element').fadeTo(500, 0.5);  // 50% opacity

// Slide visibility  
$('#element').slideDown(300);
$('#element').slideUp(300);
$('#element').slideToggle(300);

// Check if in viewport (using custom extension)
if ($('#lazy-load-element').isInViewport()) {
    // Load content when element comes into view
    loadContent('#lazy-load-element');
}

Color and Visual Effects

Color Manipulation

// Color property manipulation
$('#element').css({
    'color': '#333333',
    'background-color': 'rgba(255, 0, 0, 0.5)',
    'border-color': 'hsl(120, 50%, 75%)'
});

// Gradient backgrounds
$('#gradient-element').css({
    'background': 'linear-gradient(45deg, #ff6b6b, #4ecdc4)',
    'background-image': 'radial-gradient(circle, #ff9a9e, #fecfef)'
});

// Color animation (requires jQuery UI or custom plugin)
$('#element').animate({
    'backgroundColor': '#ff0000'  // Note: requires jQuery UI for color animation
}, 1000);

// Working with computed colors
function lightenColor($element: JQuery, factor = 0.1) {
    const currentColor = $element.css('background-color');
    // Parse RGB and lighten (would need color parsing library)
    const newColor = adjustColorBrightness(currentColor, factor);
    $element.css('background-color', newColor);
}

// Color themes
const themes = {
    light: {
        'background-color': '#ffffff',
        'color': '#333333',
        'border-color': '#cccccc'
    },
    dark: {
        'background-color': '#333333',
        'color': '#ffffff',
        'border-color': '#666666'
    }
};

function applyTheme(themeName: keyof typeof themes) {
    $('body').css(themes[themeName]);
}

Visual Effects

// Box shadow effects
$('#card').css({
    'box-shadow': '0 4px 8px rgba(0, 0, 0, 0.1)',
    'border-radius': '8px'
});

// Hover effects (CSS approach)
$('.hover-card').hover(
    function() {
        $(this).css({
            'transform': 'translateY(-2px)',
            'box-shadow': '0 8px 16px rgba(0, 0, 0, 0.15)'
        });
    },
    function() {
        $(this).css({
            'transform': 'translateY(0)',
            'box-shadow': '0 4px 8px rgba(0, 0, 0, 0.1)'
        });
    }
);

// Transform effects
$('#transform-element').css({
    'transform': 'rotate(45deg) scale(1.2) translateX(10px)',
    'transform-origin': 'center center',
    'transition': 'transform 0.3s ease'
});

// Filter effects
$('#filter-element').css({
    'filter': 'blur(2px) brightness(1.2) contrast(1.1)',
    'backdrop-filter': 'blur(10px)'
});

// Opacity and visibility transitions
$('#fade-element').css({
    'opacity': '0',
    'transition': 'opacity 0.5s ease-in-out'
});

// Trigger opacity change
setTimeout(() => {
    $('#fade-element').css('opacity', '1');
}, 1000);

Responsive and Adaptive Styling

Responsive Utilities

// Viewport-based styling
function updateResponsiveStyles() {
    const $window = $(window);
    const windowWidth = $window.width()!;
    const windowHeight = $window.height()!;
    
    if (windowWidth < 768) {
        // Mobile styles
        $('.responsive-nav').css({
            'position': 'fixed',
            'top': '0',
            'left': '0',
            'width': '100%',
            'height': '60px'
        });
    } else if (windowWidth < 1024) {
        // Tablet styles
        $('.responsive-nav').css({
            'position': 'relative',
            'width': '100%',
            'height': '80px'
        });
    } else {
        // Desktop styles
        $('.responsive-nav').css({
            'position': 'relative',
            'width': '100%',
            'height': '100px'
        });
    }
}

// Update on window resize
$(window).on('resize', updateResponsiveStyles);
updateResponsiveStyles(); // Initial call

// Container queries simulation
function updateContainerStyles() {
    $('.responsive-container').each(function() {
        const $container = $(this);
        const containerWidth = $container.width()!;
        
        if (containerWidth < 300) {
            $container.addClass('small').removeClass('medium large');
        } else if (containerWidth < 600) {
            $container.addClass('medium').removeClass('small large');
        } else {
            $container.addClass('large').removeClass('small medium');
        }
    });
}

$(window).on('resize', updateContainerStyles);

Dynamic Layout Management

// Equal height columns
function equalizeHeights(selector: string) {
    const $elements = $(selector);
    let maxHeight = 0;
    
    // Reset heights
    $elements.height('auto');
    
    // Find maximum height
    $elements.each(function() {
        const height = $(this).height()!;
        if (height > maxHeight) {
            maxHeight = height;
        }
    });
    
    // Set all to maximum height
    $elements.height(maxHeight);
}

equalizeHeights('.column');

// Masonry-like layout
function masonryLayout(containerSelector: string, itemSelector: string) {
    const $container = $(containerSelector);
    const $items = $(itemSelector);
    const containerWidth = $container.width()!;
    const itemWidth = $items.first().outerWidth()!;
    const columns = Math.floor(containerWidth / itemWidth);
    const columnHeights: number[] = new Array(columns).fill(0);
    
    $items.each(function(index) {
        const $item = $(this);
        const shortestColumn = columnHeights.indexOf(Math.min(...columnHeights));
        const left = shortestColumn * itemWidth;
        const top = columnHeights[shortestColumn];
        
        $item.css({
            'position': 'absolute',
            'left': left + 'px',
            'top': top + 'px'
        });
        
        columnHeights[shortestColumn] += $item.outerHeight()!;
    });
    
    // Set container height
    $container.height(Math.max(...columnHeights));
}

// Sticky positioning
function makeStickyNav() {
    const $nav = $('#navigation');
    const navTop = $nav.offset()!.top;
    
    $(window).on('scroll', function() {
        const scrollTop = $(window).scrollTop()!;
        
        if (scrollTop > navTop) {
            $nav.css({
                'position': 'fixed',
                'top': '0',
                'z-index': '1000'
            }).addClass('sticky');
        } else {
            $nav.css({
                'position': 'static'
            }).removeClass('sticky');
        }
    });
}

Performance Optimizations

Efficient CSS Operations

// Batch CSS changes to avoid multiple reflows
function efficientStyling($elements: JQuery) {
    // Bad: multiple reflows
    // $elements.css('width', '100px');
    // $elements.css('height', '100px'); 
    // $elements.css('margin', '10px');
    
    // Good: single reflow
    $elements.css({
        'width': '100px',
        'height': '100px',
        'margin': '10px'
    });
}

// Use classes instead of inline styles when possible
function toggleActiveState($element: JQuery, isActive: boolean) {
    // Better than setting multiple CSS properties
    $element.toggleClass('active', isActive);
}

// Cache frequently accessed elements
const $window = $(window);
const $document = $(document);
const $body = $('body');

// Debounce resize events
let resizeTimeout: number;
$window.on('resize', function() {
    clearTimeout(resizeTimeout);
    resizeTimeout = window.setTimeout(() => {
        updateResponsiveStyles();
        equalizeHeights('.column');
    }, 250);
});

// Use CSS transforms for animations (hardware accelerated)
function animateWithTransform($element: JQuery) {
    // Better performance than animating left/top
    $element.css({
        'transform': 'translateX(100px) translateY(50px)',
        'transition': 'transform 0.3s ease'
    });
}

// Minimize DOM queries
function processElements() {
    const $items = $('.processable-item'); // Query once
    
    $items.each(function() {
        const $item = $(this); // Cache jQuery object
        const width = $item.width()!; // Get value once
        
        $item.css({
            'min-width': width,
            'max-width': width * 1.5
        });
    });
}

The CSS and styling system provides comprehensive control over element appearance, layout, and visual effects with cross-browser compatibility and performance optimizations. Combined with jQuery's animation capabilities, it enables sophisticated visual interfaces while maintaining clean, maintainable code.