Modern CSS Solutions

フィード

記事のアイキャッチ画像
12 Modern CSS One-Line Upgrades
Modern CSS Solutions
Sometimes, improving your application CSS just takes a one-line upgrade or enhancement! Learn about 12 properties to start incorporating into your projects, and enjoy reducing technical debt, removing JavaScript, and scoring easy wins for user experience.Properties are explored for the following categories:Stable Upgrades: fix a hack or issue by replacing older techniquesStable Enhancements: provide an improved experience with well-supported modern propertiesProgressive Enhancements: provide an upgraded experience when these properties are supported without causing harm in unsupporting browsersStable Upgrades#The following well-supported properties can help fix a hack or long-standing issue by replacing older techniques.aspect-ratio#Have you ever used the “padding hack” to force an aspect ratio such as 16:9 for video embeds? As of September 2021, the aspect-ratio property is stable in evergreen browsers and is the only property needed to define an aspect ratio.For an HD video, you can
4ヶ月前
記事のアイキャッチ画像
How Custom Property Values are Computed
Modern CSS Solutions
Custom properties - aka “CSS variables” - seem fairly straightforward. However, there are some behaviors to be aware of regarding how the browser computes the final values. A misunderstanding of this process may lead to an unexpected or missing value and difficulty troubleshooting and resolving the issue.To help you use custom properties confidently and troubleshoot efficiently, we’ll review:how the browser determines values for any propertythe impact of “computed value time”pitfalls around using custom properties with cutting-edge CSSwhy inheritance should inform your custom property architectureComputed, Inherited, and Initial Values#When the browser parses CSS, its goal is to calculate one value per property per element in the DOM.Something you learn early on about CSS is that you can change a property’s value multiple times from multiple rules that may select the same element.Given the HTML <h2 class="card__title">, all of the following are eligible matches for the color property.b
8ヶ月前
記事のアイキャッチ画像
Modern CSS For Dynamic Component-Based Architecture
Modern CSS Solutions
The language of CSS has had an explosion of new features and improvements in the last few years. As a result, feature parity between browsers is at an all-time high, and efforts are being made to continue releasing features consistently and synchronously among evergreen browsers.Today, we will explore modern project architecture, emphasizing theming, responsive layouts, and component design. We'll learn about features to improve code organization and dig into layout techniques such as grid and container queries. Finally, we'll review real-world examples of context-aware components that use cutting-edge CSS techniques. You're sure to be inspired to expand your CSS skills and ready to create scalable, future-friendly web projects.CSS Reset Additions#Since the early days of CSS, a convention to tame cross-browser styling inconsistencies has been the CSS reset. This refers to a group of rules that do things like to remove default spacing attributes or enforce inheritance of font styles. It
1年前
記事のアイキャッチ画像
Testing Feature Support for Modern CSS
Modern CSS Solutions
The pace of the CSS language can be challenging to keep up with! Browsers release features and fixes monthly, and the CSS Working Group is constantly working on specifications. So, how do you know using a new feature is "safe" to use? And what are the considerations around making that choice?Let's review how to:find information on new featurestest for supportdetermine when to use a featuredecide whether a fallback is neededuse build tools and polyfillsFinding Out About New CSS Features#Here is a list of ways you can find out about new and upcoming CSS features:following the developer relations folks from various browser makers, like Una Kravets and Jen Simmonsreviewing and starring issues you're interested in being added to CSS in the public GitHubsubscribe to the CSS Working Group (CSSWG) blog feedcheck the release notes and feature blogs from browser enginesWebkit (Safari)FirefoxChromeconsume materials from publications and individuals who focus a lot on CSSCSS IRL by Michelle Barker
1年前
記事のアイキャッチ画像
Container Query Units and Fluid Typography
Modern CSS Solutions
Fluid typography is the term for designing font-size rules that responsively adapt the size based on the amount of available inline space. Before the availability of container query units, techniques usually relied on the viewport width - vw - unit. The viewport method is excellent for main page type, such as article headlines. However, viewport-based fluid typography doesn't quite work for narrower spaces that flex independently of the viewport, such as a grid of cards.We'll explore three ways to create dynamic fluid typography rules by leveraging container query units and CSS custom properties. You'll learn more about:creating mixins using custom propertiesmax(), min(), calc() and clamp()container queries and units:is() and :where()Previously here on ModernCSS, I presented a method that relied on using Sass to perform some calculations and produce the rules to apply viewport-based fluid typography. You may still be interested in some of the other information including tips on prevent
1年前
記事のアイキャッチ画像
Contextual Spacing For Intrinsic Web Design
Modern CSS Solutions
The user's browsing environment is not predictable. Tell other developers, and for goodness sakes, tell your designers. Let's learn how to coexist with that unpredictability by using adaptive, contextual spacing techniques.In 2018, Jen Simmons introduced the term "Intrinsic Web Design" in her talk "Everything You Know About Web Design Just Changed." She also shared the principles of intrinsic web design that we'll use as guidance:Contracting & Expanding - the way we consider how our design will adapt to a change in available spaceFlexibility - using primarily flexbox and grid in combination with newer units and functions in a way that enables our layouts to adapt at various rates to the available spaceViewport - the ability to use all four sides of the viewport as well as take advantage of viewport unitsUsing adaptive layout techniques is a trust exercise between designers, developers, and the browser.Properties and functions for intrinsic design#Let's start with a review of the founda
2年前
記事のアイキャッチ画像
Practical Uses of CSS Math Functions: calc, clamp, min, max
Modern CSS Solutions
There are currently four well-supported math functions in CSS. I've found each of them to be extremely useful in my daily work. These CSS functions can be used in perhaps unexpected ways, such as within gradients and color functions and in combination with CSS custom properties. We'll learn the syntax for each, view basic demos of their functionality, and explore practical use cases.calc()#Practical purpose of calc(): performing basic math operations, with the ability to interpolate between unit types (ex. rem to vw).This math function has the longest cross-browser support of the four functions we're exploring. It has a wide range of uses for any time you'd like to be able to do client-side math within your styles.For example, you may want something to take up most of the viewport height except the height of the navigation. For this purpose, you can mix units to pass a relative vh (view height) unit with an absolute pixel unit:.content { height: calc(100vh - 60px);}As the viewport resi
3年前
記事のアイキャッチ画像
Modern CSS Upgrades To Improve Accessibility
Modern CSS Solutions
Accessibility is a critical skill for developers doing work at any point in the stack. For front-end tasks, modern CSS provides capabilities we can leverage to make layouts more accessibly inclusive for users of all abilities across any device.This post will cover a range of topics:Focus VisibilityFocus vs. Source OrderDesktop Zoom and ReflowSizing Interactive TargetsRespecting Color and Contrast SettingsAccessibility Learning ResourcesWhat Does "Accessible" Mean?#Accessible websites are ones that are created without barriers for users of various abilities to access content or perform actions. An internationally agreed-upon standard called the Web Content Accessibility Guidelines - or WCAG - provides success criteria to help guide you towards creating accessible experiences.Common accessibility barriers include:inability to see content or distinguish interface elements due to poor color contrastreduced or removed access to non-text content such as within images or charts due to failing
3年前
記事のアイキャッチ画像
Developing For Imperfect: Future Proofing CSS Styles
Modern CSS Solutions
How do we plan future-proof styles in a world with an infinite degree of device and user ability variance? Let's explore how things can break and how modern CSS provides solutions.This episode will cover handling for:variable content length and overflowunpredictable media sizesinternationalizationaccessibility-related user settingsWe'll explore creating a robust comment thread component. Here's our starting point - an exact mimic of the layout you received from design, good job!CSS for "Initial Comment Thread".comment-list { list-style: none; padding: 0.5rem; margin: 0; display: grid; gap: 1.5rem;}.comment .comment-list { grid-column-start: 2; grid-column-end: -1; padding: 0;}.comment { display: grid; grid-template-columns: 64px 1fr; gap: 1rem;}.comment-body { display: grid; gap: .5rem; color: #444;}.comment-meta { color: #767676; font-size: .875rem;}.comment-body a { color: inherit;}.comment-meta a { color: mediumvioletred;} @baywriter 15 mins ago Lemon drops danish soufflé gummies dr
3年前
記事のアイキャッチ画像
Guide to Advanced CSS Selectors - Part Two
Modern CSS Solutions
Continuing from part one, this episode will focus on the advanced CSS selectors categorized as pseudo classes and pseudo elements and practical applications for each. We'll especially try to make sense of the syntax for nth-child.Part Two (this article):#Pseudo classes - ex: :checked / :focusPseudo elements - ex: ::before / ::afterAdditional resourcesPart One:#CSS Specificity and the CascadeUniversal selector - *Attribute selector - [attribute]Child combinator - >General sibling combinator - ~Adjacent sibling combinator - +Pseudo Classes#This is the largest category, and also the most context-dependent.Pseudo classes are keywords that are applied when they match the selected state or context of an element.These vastly increase the capabilities of CSS and enable functionality that in the past was often erroneously relegated to JavaScript.Some selectors are stateful::focus:hover:visited:target:checkedWhile others attach to the order of elements::nth-child() / :nth-of-type():first-child /
3年前
記事のアイキャッチ画像
Guide to Advanced CSS Selectors - Part One
Modern CSS Solutions
Whether you choose to completely write your own CSS, or use a framework, or be required to build within a design system - understanding selectors, the cascade, and specificity are critical to developing CSS and modifying existing style rules.You're probably quite familiar with creating CSS selectors based on IDs, classes, and element types. And you've likely often used the humble space character to select descendants.In this two-part mini-series, we'll explore some of the more advanced CSS selectors, and examples of when to use them.Part One (this article):#CSS Specificity and the CascadeUniversal selector - *Attribute selector - [attribute]Child combinator - >General sibling combinator - ~Adjacent sibling combinator - +Part Two:#Pseudo classes - ex: :checked / :focusPseudo elements - ex: ::before / ::afterAdditional resourcesCSS Specificity and the Cascade#A key concept to successfully setting up CSS selectors is understanding what is known as CSS specificity, and the "C" in CSS, whic
3年前
記事のアイキャッチ画像
The 3 CSS Methods for Adding Element Borders
Modern CSS Solutions
When it comes to CSS, sometimes a border is not really a border.In this episode, we'll cover the differences between:borderoutlinebox-shadowWe'll also discuss when you might use one over the other.Refresher on the CSS Box Model#A key difference between our three border methods is where they are placed on an element and how they affect its dimensions. This behavior is controlled by the CSS box model.the border is precisely the boundary of the element, sitting between its padding and margin, and it's width will impact the computed element dimensionsthe outline is next to but outside of the border, overlapping both box-shadow and margin, but not affecting the element's dimensionsby default, box-shadow extends out from edge of the border covering the amount of space in the direction(s) defined, and it will also not affect the element's dimensionsborder Syntax and Usage#Borders have been a standard in design since the beginning of the web.An important difference compared to the other two me
3年前
記事のアイキャッチ画像
Pure CSS Shapes 3 Ways
Modern CSS Solutions
Modern CSS - and modern browser support - provides us three excellent methods to create pure, basic CSS shapes. In this tutorial, we will examine how to create CSS triangles using:borderslinear gradientsclip-pathMethod 1: Borders#This is the first trick I learned to create CSS triangles, and it's still a solid standby.Given a zero width and zero height element, any values provided border directly intersect and are the only visible indication of an element. This intersection is what we can take advantage of to create a triangle shape.To illustrate how this works, we'll supply a different border color to each side:.triangle { border: 10px solid blue; border-right-color: red; border-bottom-color: black; border-left-color: green;}Which produces the following, in which you can see we've essentially already achieved 4 triangle shapes:In order to create this as a single triangle instead, we first decide which direction we want the triangle pointing. So, if we want it pointing to the right, si
4年前
記事のアイキャッチ画像
Custom CSS Styles for Form Inputs and Textareas
Modern CSS Solutions
We're going to create custom form input and textarea styles that have a near-identical appearance across the top browsers. We'll specifically style the input types of text, date, and file, and style the readonly and disabled states.Read on to learn how to:reset input stylesuse hsl for theming of input statesensure all states meet contrast requirementsretain a perceivable :focus state for Windows High Contrast modeNow available: my egghead video course Accessible Cross-Browser CSS Form Styling. You'll learn to take the techniques described in this tutorial to the next level by creating a themable form design system to extend across your projects.This is the fourth installment in the Modern CSS form field mini-series. Check out episodes 18-20 to learn how to style other common form field types including radio buttons, checkboxes, and selects.Common Issues with Native Input Styles#There is a bit more parity between text input styles than we saw with radios, checkboxes, and selects, but in
4年前
記事のアイキャッチ画像
Custom Select Styles with Pure CSS
Modern CSS Solutions
Modern CSS gives us a range of properties to achieve custom select styles that have a near-identical initial appearance for single, multiple, and disabled select elements across the top browsers.A few properties and techniques our solution will use:clip-path to create the custom dropdown arrowCSS grid layout to align the native select and arrowcustom CSS variables for flexible stylingem units for relative sizingNow available: my egghead video course Accessible Cross-Browser CSS Form Styling. You'll learn to take the techniques described in this tutorial to the next level by creating a themable form design system to extend across your projects.Common Issues with Native Selects#As with all form field types, <select> varies across browsers in its initial appearance.From left to right, here is the initial appearance for <select> in Firefox, Chrome, and Safari:The differences include box size, font-size, line-height, and most standout is the difference in how the dropdown indicator is style
4年前
記事のアイキャッチ画像
Pure CSS Custom Checkbox Style
Modern CSS Solutions
We'll create custom, cross-browser, theme-able, scalable checkboxes in pure CSS with the following:currentColor and CSS custom properties for theme-abilityem units for relative sizinguse of pseudo elements for the :checked indicatorCSS grid layout to align the input and labelMany of the concepts here overlap with our custom styled radio buttons from episode 18, with the addition of styling for the :disabled stateNow available: my egghead video course Accessible Cross-Browser CSS Form Styling. You'll learn to take the techniques described in this tutorial to the next level by creating a themable form design system to extend across your projects.Checkbox HTML#In the radio buttons article, we explored the two valid ways to markup input fields. Much like then, we will select the method where the label wraps the input.Here's our base HTML for testing both an unchecked and checked state:<label class="form-control"> <input type="checkbox" name="checkbox" /> Checkbox</label><label class="form-
4年前
記事のアイキャッチ画像
Pure CSS Custom Styled Radio Buttons
Modern CSS Solutions
Using a combination of the following properties, we can create custom, accessible, cross-browser, theme-able, scalable radio buttons in pure CSS:currentColor for theme-abilityem units for relative sizingappearance: none for full restyling accessCSS grid layout to align the input and labelHead's up: A lot of these styles overlap with the episode on custom checkbox styles which you might be interested in reading next!Now available: my egghead video course Accessible Cross-Browser CSS Form Styling. You'll learn to take the techniques described in this tutorial to the next level by creating a themable form design system to extend across your projects.Radio Button HTML#There are two appropriate ways to layout radio buttons in HTML.The first wraps the input within the label. This implicitly associates the label with the input that its labeling, and also increases the hit area to select the radio.<label> <input type="radio" name="radio" /> Radio label text</label>The second is to have the inp
4年前
記事のアイキャッチ画像
Announcing Style Stage: A Community CSS Showcase
Modern CSS Solutions
Dear CSS community:I invite you to participate in a new project where you have the opportunity to challenge both your CSS and web design skills while learning in public.About Style Stage#StyleStage.dev is not just an informational landing page about the project - it is the foundational HTML which is intended to be restyled by contributors - like you!Style Stage started as a wild idea to reanimate the spirit ofCSS Zen Garden which was created by Dave Shea and that provided a demonstration of "what can be accomplished through CSS-based design" until submissions stopped in 2013.Things in CSS-land have improved a lot since then, including the available properties, the tools we have available to build with, our greater understanding of addressing accessibility concerns, and increased awareness of performance impacts.If you missed the launch live stream, here's the lightly edited full recorded Twitch broadcast, or by topic in the Twitch highlight collection. We covered a lot of the things in
4年前
記事のアイキャッチ画像
3 Popular Website Heroes Created With CSS Grid Layout
Modern CSS Solutions
This episode explores creating website heroes - aka "headers" - with one of my favorite ways to use CSS grid layout: by turning it into a canvas.Support notice: The essential properties used in these techniques - grid-template-areas and object-fit - are not supported below IE 16. Good news - that still means they are about 96% supported!Inspired by my years in marketing, here are the three layouts we're going to create:#1: Marketing Call-to-Action (CTA) and Image#2: Text Overlay on Background Image#3: Two-Column with Copy and FormBase HTML and CSS Grid Setup#In the not-too-distant past, the way to achieve most of these layouts required the use of position: absolute.With grid, we can upgrade from that solution and gain responsive, dynamic positioning superpowers!Here's our starting point for HTML:<header> <div class="hero__content"> <h1>Product</h1> <p>You really need this product, so hurry and buy it today!</p> <a href="#" class="button">Buy Now</a> </div> <img src="http://placecorgi.c
4年前
記事のアイキャッチ画像
3 CSS Grid Techniques to Make You a Grid Convert
Modern CSS Solutions
CSS grid layout can feel daunting. In fact, I avoided it for several years and was a diehard flexbox fan.Then I found the following 3 powerful properties/techniques in grid that completely changed my tune.Spoiler, here's a tweet with all of them. Keep reading to learn a bit more!View tweet1: Switch the Grid Flow Axis#I first desired this behavior when I wanted X-axis alignment of variable width items, and also desired to leverage gap.The Code#grid-auto-flow: column;What it does#Default grid flow is oriented to "row" layout, which is complementary to block layout, where items flow down the page along the Y-axis.This switches that default behavior to "column" which means items default to flowing along the X-axis.Things to note#items will take as much room as needed to contain their content up until the max width of the container, at which point text will break to new linesthere is a risk of overflow because of lack of "wrapping" behavior in grid, which means assigning this property will
4年前
記事のアイキャッチ画像
Expanded Use of `box-shadow` and `border-radius`
Modern CSS Solutions
This episode will explore expanded usage of box-shadow and border-radius and conclude with a landing page demo using these properties to enhance the image presentation.You will learn:the expanded syntax of border-radius, and when to use which type of units to set valueshow to create multiple box-shadow layersabout the box-shadow value insethow to "hack" box-shadow with inset to apply popular image filter techniquesOverview of border-radius#Kids these days will never have to deal with creating a gif for each corner of a div that you want to appear rounded 😂 Truly, the release and eventual support of border-radius was one of the most significant milestones in CSS.For a refresher, here's how it's often used:border-radius: 50%;Which for a square element will result in a circle appearance.Or scale it back for just a slight roundedness to otherwise sharply square corners, such as for a button or card where you might use:border-radius: 8px;One way to begin to take this a bit further is to us...
4年前
記事のアイキャッチ画像
Container Query Solutions with CSS Grid and Flexbox
Modern CSS Solutions
True container queries are a much asked for CSS feature that would be a complement to media queries but be placed on container elements instead of the viewport.Experimental CSS container queries are here! Here's Miriam Suzanne's container queries proposal explainer which has an experimental prototype in Chrome Canary. After you download Canary, visit chrome://flags to search for and enable container queries. For more info, review my primer on container queries.Using grid and flexbox, we can create styles that respond to container and content widths and overcome some of the pain points that container queries are proposed to resolve.We'll cover:⏸ Use of CSS grid layout and flexbox to achieve container dependent adjustments from equal-width columns to row layout🏆 The "holy grail" solution to variable-width breakpoint columns🚀 Implementing CSS custom variables to make the solutions as scalable as possibleSkip to the solutions >Understanding the Problem#When Ethan Marcotte introduced the ...
4年前
記事のアイキャッチ画像
Generating `font-size` CSS Rules and Creating a Fluid Type Scale
Modern CSS Solutions
Let's take the mystery out of sizing type. Typography is both foundational to any stylesheet and the quickest way to elevate an otherwise minimal layout from drab to fab. If you're looking for type design theory or how to select a font, that's outside the scope of this article. The goal for today is to give you a foundation for developing essential type styles in CSS, and terms to use if you wish to explore any topics deeper.This episode covers:recommended units for font-sizegenerating ratio-based font-size values with Sassrecommended properties to prevent overflow from long words/names/URLsdefining viewport-aware fluid type scale rules with clamp()additional recommendations for dealing with typeDefining "Type Scale"#The simplified definition: "type scale" for the web refers to properties such as font-size, line-height, and often margin, that work together to create vertical rhythm in your design. These can be arbitrarily selected ("it just looks good"), or be based on the idea of a "m
4年前
記事のアイキャッチ画像
Resource: The Complete Guide to Centering in CSS
Modern CSS Solutions
How could I write a series called "Modern CSS Solutions to old CSS problems" without covering the classic question:"How do I center a div?"Well, this new resource has you covered! We'll look at 3 categories:Vertically and Horizontally (XY)Vertical (Y)Horizontal (X)Each category shows solutions that explore using grid, flexbox, and block element layout.Check out the full guide or jump to one of the following sections:Vertically and Horizontally (XY)XY Grid SolutionXY Flexbox SolutionXY Alternative Flexbox SolutionXY Centering for Block ElementsVertical Centering (Y)Y Grid SolutionY Flexbox SolutionY Centering for Block ElementsHorizontal Centering (X)X Grid SolutionX Flexbox SolutionX Centering for Block ElementsX Centering for Dynamically Positioned Elements
4年前
記事のアイキャッチ画像
Icon Button CSS Styling Guide
Modern CSS Solutions
This guide will build on the previous episode "CSS Button Styling Guide" to explore the use case of icon buttons. We'll cover icon + text as well as icon-only buttons.Note: With SVG now having excellent support, the preferred practice is to use it for icon systems vs. icon fonts. We will not dive into SVGs specifically, but we will assume SVG icons are in use.Icon + Text Button#First, let's do the easier extend from our current buttons, and drop an svg icon next to the text:<a href="javascript:;" class="button"> <svg class="button__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" focusable="false" > <path d="M32 12.408l-11.056-1.607-4.944-10.018-4.944 10.018-11.056 1.607 8 7.798-1.889 11.011 9.889-5.199 9.889 5.199-1.889-11.011 8-7.798z" ></path> </svg> Button Link</a>There are 3 key features about the SVG for the icon + text use case:Use of a new button__icon classThe viewBox value is tight to the icon boundaries, ideally a square for best results across
4年前
記事のアイキャッチ画像
CSS Button Styling Guide
Modern CSS Solutions
This guide will explore the ins and outs of styling an accessible, extensible button appearance for both link and button elements.Topics covered include:reset styles for a and buttondisplay, visual, size, and text stylesaccessible styling considerationsextended styles for common scenariosOh, the button (or is it a link?). I've battled the button since the days of hover delay from waiting for a second image to load, through image sprites, and then was immensely relieved when border-radius, box-shadow and gradients arrived on the scene.But... we took button styling too far, and somewhere along the way completely lost sight of what it really means to be a button, let alone an accessible button (or link).STOP! Go read this excellent article: Links vs. Buttons in Modern Web Applications to understand when it's appropriate to use a versus buttonWe'll look at what properties are required to visually create a button appearance for both a and button, and additional details required to ensure th
4年前
記事のアイキャッチ画像
Solutions to Replace the 12-Column Grid
Modern CSS Solutions
Let's create simplified responsive grid systems using both CSS grid and flexbox and ditch the bulk of 12-column grid systems from heavy frameworks.If you haven't really looked into grid, or rely on frameworks to think about flexbox for you, this will help you level up your understanding 🚀Looking across the web, you will often see content laid out in a few select flavors:fullwidth of its containertwo equal-width columnsthree equal-width columnsfour equal-width columnsUsually, this is accomplished by a considerable amount of utility classes setting widths across breakpoints.Between CSS grid and flexbox, and with the aforementioned layouts in mind, we can greatly reduce the setup of responsive grid columns.For both solutions, we will create just two classes and be able to handle from 1-4 columns of content that responsively resizes equally 🙌Note: These solutions as-is work best for defining primary page layout containers, but we'll end with some suggestions on filling the gap for other ...
4年前
記事のアイキャッチ画像
CSS-Only Accessible Dropdown Navigation Menu
Modern CSS Solutions
This technique explores using:Animation with CSS transition and transformUsing the :focus-within pseudo-classCSS grid for positioningdynamic centering techniqueAccessibility considerations for dropdown menusIf you've ever pulled your hair out dealing with the concept of "hover intent", then this upgrade is for you!Before we get too far, while our technique 100% uses only CSS, there is a need to add some Javascript for a more comprehensively accessible experience. There is also a polyfill needed for a key feature to make this work - :focus-within - for the most reliable support. But we've still greatly improved from the days of needing one or more jQuery plugins to accomplish the visual effects.Accessibility update - 08/18/20: A huge thanks to Michael Fairchild of Deque (and creator of the excellent resource a11ysupport.io) for testing the original solution across various assistive technology. The CSS-only method needs some Javascript to fully meet WCAG 2.1. In particular, javascript ne
4年前
記事のアイキャッチ画像
Responsive Image Gallery With Animated Captions
Modern CSS Solutions
.demo .demo--content { background-color: transparent; padding: 1rem; }Responsively resizing images is a common need, and modern CSS provides tools for ensuring a consistent aspect-ratio while not distorting the images. And grid gives us flexibility for a gallery layout as well as positioning multiple elements in a shared space.This responsive gallery technique explores using:object-fit for responsive image scalingaspect-ratio for consistent image sizesA CSS Grid trick to replace absolute positioningCSS transforms for animated effectshandling for touch devicesrespecting reduced motionGallery HTML#Here is our initial HTML, which is an ul where each li contains a figure with the image and figcaption:<ul class="gallery" role="list"> <li> <figure> <img alt="" src="https://picsum.photos/550/300" /> <figcaption>Candy canes ice cream</figcaption> </figure> </li> <li> <figure> <img alt="" src="https://picsum.photos/400" /> <figcaption>Ice cream biscuit</figcaption> </figure> </li> <li> <figure>
4年前
記事のアイキャッチ画像
Totally Custom List Styles
Modern CSS Solutions
This tutorial will show how to use CSS grid layout for easy custom list styling in addition to:Data attributes as the content of pseudo elementsCSS counters for styling ordered listsCSS custom variables for per-list item stylingResponsive multi-column listsUpdate: The ::marker pseudo selector is now well supported in modern browsers. While this tutorial includes handy CSS tips for the items listed above, you may want to jump to the ::marker solutionList HTML#First we'll setup our HTML, with one ul and one li. I've included a longer bullet to assist in checking alignment, spacing, and line-heihgt.<ul role="list"> <li>Unordered list item</li> <li>Cake ice cream sweet sesame snaps dragée cupcake wafer cookie</li> <li>Unordered list item</li></ul><ol role="list"> <li>Ordered list item</li> <li>Cake ice cream sweet sesame snaps dragée cupcake wafer cookie</li> <li>Ordered list item</li></ol>Note the use of role="list". At first, it may seem extra, but we are going to remove the inherent lis
4年前
記事のアイキャッチ画像
Pure CSS Smooth-Scroll "Back to Top "
Modern CSS Solutions
"Back to top" links may not be in use often these days, but there are two modern CSS features that the technique demonstrates well:position: stickyscroll-behavior: smoothI first fell in love with "back to top" links - and then learned how to do them with jQuery - on one of the most gorgeous sites of 2011: Web Designer Wall.The idea is to provide the user with a "jump link" to scroll back to the top of the website and was often used on blogs of yore.Here's what we will learn to achieve:About position: sticky#This newer position value is described as follows on caniuse:Keeps elements positioned as "fixed" or "relative" depending on how it appears in the viewport. As a result, the element is "stuck" when necessary while scrolling.The other important note from caniuse data is that you will need to offer it prefixed for the best support. Our demo will fallback to position: fixed which will achieve the main goal just a bit less gracefully.About scroll-behavior: smooth#This is a very new prop
4年前
記事のアイキャッチ画像
CSS-Only Full-Width Responsive Images 2 Ways
Modern CSS Solutions
In the not to distant past when jQuery was King of the Mountain and CSS3 was still worth being designated as such, the most popular tool for responsive background images was the Backstretch jQuery plugin.I used this plugin on ~30 sites prior to the following property becoming more supported (aka IE < 9 dropping in total market share):background-size: cover;According to caniuse.com, this property and value have been well supported for over 9 years! But websites that are intertwined with using Backstretch or another homegrown solution may not yet have updated.The alternative method makes use of the standard img tag, and uses the magic of:object-fit: cover;Let's look at how to use each solution, and learn when to select one over the other.Using background-size: cover#A decade of my background was creating highly customized WordPress themes and plugins for enterprise websites. So using the example of templated cards, here's how you might set up using the background-size: cover solution.Fir
4年前
記事のアイキャッチ画像
Equal Height Elements: Flexbox vs. Grid
Modern CSS Solutions
Once upon a time (approximately 2013), I wrote a jQuery plugin to calculate equal height columns. It ensured that the very specific scenario of a row with three columns would keep the content boxes equal height no matter the length of the content they contained. The dominant layout method at the time - floats - did not handle this problem.Flexbox Solution#When flexbox arrived on the scene, this became possible with:.flexbox { display: flex;}Amazing! By default, direct children line up in a row and have a "stretch" applied so they are equal height 🙌But then you add two .column divs as children and... the contents of the columns appear unequal again 😔The fix is:.flexbox { display: flex; // Ensure content elements fill up the .column .element { height: 100%; }}Now the columns will appear equal height and grow with the content of .element.Join my newsletter for article updates, CSS tips, and front-end resources!Don’t fill this out if you're human: Email Subscribe Grid Solution#With grid,...
4年前
記事のアイキャッチ画像
Keep the Footer at the Bottom: Flexbox vs. Grid
Modern CSS Solutions
For many years, I constantly referred to this article by Matthew James Taylor for a method to keep a webpage footer at the bottom of the page regardless of the main content length. This method relied on setting an explicit footer height, which is not scalable but a very good solution BF (Before Flexbox).If you mostly deal with SPA development, you may be confused about why this problem is still around, but it's still a possibility to find your footer floating up for:login pagesblog/news articles (with no ads...)interstitial pages of a flow like confirming actionsproduct listing pagescalendar event detailsThere are two ways to handle this with modern CSS: flexbox and grid.Here's the demo, defaulted to the flexbox method. If you open the full Codepen, you can swap the $method variable to grid to view that alternative.Read on past the demo to learn about each method.By Stephanie Eckles (@5t3ph)Flexbox Method#This method is accomplished by defining:body { min-height: 100vh; display: flex;
4年前