所有动态
- 一小时前
-
CSS Image Filter Effects
CSS Image Filter Effects CSS Filters The CSS filter property is used to add visual effects (like blur and saturation) to elements. Within the filter property, you can use the following CSS functions: blur() brightness() contrast() drop-shadow() grayscale() hue-rotate() invert() opacity() saturate() sepia() The CSS blur() Function The blur() filter function applies a blur effect to an element. A larger value will create more blur. If no value is specified, 0 is used (no effect). Example Apply different blur effects to <img> elements: #img1 { filter: blur(2px); } #img2 { filter: blur(6px); } Try it Yourself » The CSS brightness() Function The brightness() filter function adjusts the brightness of an element. 100% is default, and represents the original brightness Values over 100% will provide brighter results Values under 100% will provide darker results 0% will make the image completely black Example Make an image brighter and darker than the original: #img1 { filter: brightness(150%); } #img2 { filter: brightness(50%); } Try it Yourself » The CSS contrast() Function The contrast() filter function adjusts the contrast of an element. 100% is default, and represents the original contrast Values over 100% increases the contrast Values under 100% decreases the contrast 0% will make the image completely gray Example Increase and decrease the contrast for an image: #img1 { filter: contrast(150%); } #img2 { filter: contrast(50%); } Try it Yourself » The CSS drop-shadow() Function The drop-shadow() filter function applies a drop-shadow effect to an image. Example Add different drop-shadow effects to an image: #img1 { filter: drop-shadow(8px 8px 10px gray); } #img2 { filter: drop-shadow(10px 10px 7px lightblue); } Try it Yourself » The CSS grayscale() Function The grayscale() filter function converts an image to grayscale. 100% (or 1) will make the image completely grayscale 0% (or 0) will have no effect Example Set various grayscale for an image: #img1 { filter: grayscale(1); } #img2 { filter: grayscale(60%); } #img3 { filter: grayscale(0.4); } Try it Yourself » The CSS hue-rotate() Function The hue-rotate() filter function applies a color rotation to an element. This function applies a hue rotation on the image. The value defines the number of degrees around the color circle the image will be adjusted. A positive hue rotation increases the hue value, while a negative rotation decreases the hue value. 0deg represents the original image. Example Set various color rotations for an image: #img1 { filter: hue-rotate(200deg); } #img2 { filter: hue-rotate(90deg); } #img3 { filter: hue-rotate(-90deg); } Try it Yourself » The CSS invert() Function The invert() filter function inverts the color of an image. 100% (or 1) will fully invert the colors 0% (or 0) will have no effect Example Invert the colors of an image: #img1 { filter: invert(0.3); } #img2 { filter: invert(70%); } #img3 { filter: invert(100%); } Try it Yourself » The CSS opacity() Function The opacity() filter function applies an opacity effect to an element. 100% (or 1) will have no effect 50% (or 0.5) will make the element 50% transparent 0% (or 0) will make the element completely transparent Example Set various opacity for an image: #img1 { filter: opacity(80%); } #img2 { filter: opacity(50%); } #img3 { filter: opacity(0.2); } Try it Yourself » The CSS saturate() Function The saturate() filter function adjusts the saturation (color intensity) of an element. 100% (or 1) will have no effect 0% (or 0) will make the element completely unsaturated 200% (or 2) will make the element super saturated Example Set various saturations for an image: #img1 { filter: saturate(0); } #img2 { filter: saturate(100%); } #img3 { filter: saturate(200%); } Try it Yourself » The CSS sepia() Function The sepia() filter function converts an image to a sepia tone (a warmer, more brown/yellow color). 0% (or 0) will have no effect 100% (or 1) applies full sepia effect Example Set various sepia for an image: #img1 { filter: sepia(1); } #img2 { filter: sepia(60%); } #img3 { filter: sepia(0.4); } Try it Yourself » CSS Filter Functions The following table lists the CSS filter functions: Function Description blur() Applies a blur effect to an element brightness() Adjusts the brightness of an element contrast() Adjusts the contrast of an element drop-shadow() Applies a drop-shadow effect to an image grayscale() Converts an image to grayscale hue-rotate() Applies a color rotation to an element invert() Inverts the color of an image opacity() Applies an opacity effect to an element saturate() Adjusts the saturation (color intensity) of an element sepia() Converts an image to sepia ★ +1 Sign in to track progress
-
CSS Centering Images
CSS Centering Images Centering Images With CSS, you can center images with several methods. An image can be centered horizontally, vertically, or both. Center an Image Horizontally To display a horizontally centered image, we can use margin: auto; or display: flex;. 1. Using margin: auto One way to center an image horizontally on a page is to use margin: auto. Since the <img> element is an inline element by default (and margin: auto does not have any effect on inline elements) we must convert the image to a block element, with display: block. In addition, we have to define a width. The width of the image must be smaller than the width of the page. Here is a horizontally centered image using margin: auto: Example Horizontally centered image using margin: auto: img { display: block; margin: auto; width: 50%; } Try it Yourself » 2. Using display: flex Another way to center an image horizontally on a page is to use display: flex. Here, we put the <img> element inside a <div> container. We add the following CSS to the div container: display: flex justify-content: center (centers the image horizontally in the div container) Then, we set a width for the image. The width of the image must be smaller than the width of the page. Here is a horizontally centered image using display: flex: Example Horizontally centered image using display: flex: div { display: flex; justify-content: center; } img { width: 50%; } Try it Yourself » Vertical and Horizontal Centering To display an image that is both vertically and horizontally centered (true centering), we can use display: flex; or display: grid;. 1. Using display: flex To display an image that is both vertically and horizontally centered with flexbox, we use a combination of: display: flex; justify-content: center; (centers the image horizontally in the container) align-items: center; (centers the image vertically in the container) height: 600px; (the height of the container) Here, we also put the <img> element inside a <div> container. Then, we set a width for the image (must be smaller than the width of the container). Here is a vertically and horizontally centered image with flexbox: Example True centering using display: flex: div { display: flex; justify-content: center; align-items: center; height: 600px; border: 1px solid black; } img { width: 50%; } Try it Yourself » 2. Using display: grid To display an image that is both vertically and horizontally centered with grid, we use a combination of: display: grid; place-items: center; (centers the image horizontally and vertically in the container) height: 600px; (the height of the container) Here, we also put the <img> element inside a <div> container. Then, we set a width for the image (must be smaller than the width of the container). Here is a vertically and horizontally centered image with grid: Example True centering using display: grid: div { display: grid; place-items: center; height: 600px; border: 1px solid black; } img { width: 50%; } Try it Yourself » ★ +1 Sign in to track progress
-
CSS Responsive Modal Images
CSS Responsive Modal Images Responsive Modal Image Gallery A modal image gives a user the ability to display a larger version of an image, without navigating away from the current page. When a user clicks on a modal image, it shows a popup window that appears on top of the main content of the webpage, often with a semi-transparent background. The modal must be closed by the user, typically with a "close" button or an "X" sign in top-right corner. This example demonstrates how to use HTML, CSS and JavaScript together, to create a responsive modal image gallery. We use CSS to create a modal window (dialog box), and hide it by default. Then, we use a JavaScript to show the modal window with the correct image inside, when a user clicks on the image: × × × × Example <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } h1 { text-align: center; padding: 20px; } .gallery { display: flex; flex-wrap: wrap; justify-content: flex-start; padding: 0 15px; } .gallery-item { position: relative; width: calc(25% - 20px); height: auto; margin: 10px; cursor: pointer; transition: transform 0.5s ease; } .gallery-item:hover { transform: scale(1.1); } /* The Modal (background) */ .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); align-items: center; justify-content: center; transition: opacity 0.5s ease; } /* Modal content (image) */ .modal-content { position: relative; width: 90%; height: auto; max-width: 90%; max-height: 90%; border-radius: 5px; overflow: hidden; animation: zoomIn 0.5s; } @keyframes zoomIn { from {transform: scale(0.6);} to {transform: scale(1);} } .modal.show { display: flex; opacity: 1; } /* Close button */ .close { position: absolute; top: 10px; right: 15px; color: #ffffff; font-size: 35px; font-weight: bold; cursor: pointer; transition: transform 0.3s; } /* Caption of modal image */ .caption { position: absolute; bottom: 15px; width: 100%; text-align: center; color: #ffffff; font-size: 24px; } @media screen and (max-width: 768px) { .gallery-item { width: calc(50% - 20px); } } @media screen and (max-width: 480px) { .gallery-item { width: calc(100% - 20px); } } </style> </head> <body> <h1>Responsive Modal Images</h1> <div class="gallery"> <img src="img_5terre.jpg" alt="Cinque Terre" class="gallery-item"> <img src="img_forest.jpg" alt="Forest" class="gallery-item"> <img src="img_lights.jpg" alt="Northern Lights" class="gallery-item"> <img src="img_mountains.jpg" alt="Mountains" class="gallery-item"> </div> <div id="modal1" class="modal"> <span class="close">×</span> <img src="img_5terre.jpg" alt="Cinque Terre" class="modal-content"> <div class="caption"></div> </div> <div id="modal2" class="modal"> <span class="close">×</span> <img src="img_forest.jpg" alt="Forest" class="modal-content"> <div class="caption"></div> </div> <div id="modal3" class="modal"> <span class="close">×</span> <img src="img_lights.jpg" alt="Northern Lights" class="modal-content"> <div class="caption"></div> </div> <div id="modal4" class="modal"> <span class="close">×</span> <img src="img_mountains.jpg" alt="Mountains" class="modal-content"> <div class="caption"></div> </div> <script> function openModal(modalId, caption) { let modal = document.getElementById(modalId); modal.style.display = "flex"; modal.classList.add("show"); let message = modal.querySelector(".caption"); message.innerText = caption; } function closeModal(modalId) { let modal = document.getElementById(modalId); modal.classList.remove("show"); setTimeout(function () { modal.style.display = "none"; modal.querySelector(".caption").innerText = ""; }, 300); } </script> </body> </html> Try it Yourself » ★ +1 Sign in to track progress
-
CSS Styling Images
CSS Styling Images Learn how to style images using CSS. Rounded Images You can use the border-radius property to create rounded images: Example Rounded Image: img { border-radius: 8px; } Try it Yourself » Example Circled Image: img { border-radius: 50%; } Try it Yourself » Tip: Look at the CSS Image Shapes chapter to learn how to shape (clip) images to circles, ellipses and polygons. Thumbnail Images Use the border property to create thumbnail images: Example img { border: 1px solid #ddd; border-radius: 4px; padding: 5px; width: 150px; } Try it Yourself » Thumbnail image as a link: Example img { border: 1px solid #ddd; border-radius: 4px; padding: 5px; width: 150px; } img:hover { box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5); } Try it Yourself » Responsive Images Responsive images will automatically adjust to fit the size of the screen. Resize the browser window to see the effect: If you want an image to scale down if it has to, but never scale up to be larger than its original size, add the following: Example img { max-width: 100%; height: auto; } Try it Yourself » Tip: Read more about Responsive Web Design in our CSS RWD Tutorial. Polaroid Images / Cards Cinque Terre Northern Lights Example div.polaroid { width: 80%; background-color: white; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); } img {width: 100%} div.container { text-align: center; padding: 10px 20px; } Try it Yourself » Responsive Image Gallery CSS can be used to create responsive image galleries. This example use media queries to re-arrange the images on different screen sizes. Resize the browser window to see the effect: Cinque Terre Green Forest Northern Lights Mountains Example @media only screen and (max-width: 768px) { div.gallery-item { width: calc(50% - 20px); } } @media only screen and (max-width: 480px) { div.gallery-item { width: calc(100% - 20px); } } Try it Yourself » Tip: Read more about Responsive Web Design in our CSS RWD Tutorial. Image Styling Subpages Continue learning about CSS image styling: Image Effects - opacity, text positioning, fade overlays Hover Overlays - slide effects, flip ★ +1 Sign in to track progress
-
CSS Tooltip
CSS Tooltip CSS Tooltip A CSS tooltip is used to specify extra information about something when the user moves the mouse pointer over an element: Top Tooltip text Right Tooltip text Bottom Tooltip text Left Tooltip text CSS Create a Basic Tooltip Create a tooltip that appears when the user moves the mouse over an element: Example <style> /* Tooltip container */ .tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; /* Add dots under the hoverable text */ cursor: pointer; } /* Tooltip text */ .tooltiptext { visibility: hidden; /* Hidden by default */ width: 130px; background-color: black; color: #ffffff; text-align: center; padding: 5px 0; border-radius: 6px; position: absolute; z-index: 1; /* Ensure tooltip is displayed above content */ } /* Show the tooltip text on hover */ .tooltip:hover .tooltiptext { visibility: visible; } </style> <div class="tooltip">Hover over me <span class="tooltiptext">Some tooltip text</span> </div> Try it Yourself » Example Explained HTML: Use a container element (like <div>) and add the "tooltip" class to it. When the user mouse over this <div>, it will show the tooltip text. The tooltip text is placed inside an inline element (like <span>) with class="tooltiptext". CSS: The tooltip class use position:relative, which is needed to position the tooltip text (position:absolute). Tip: See examples below on how to position the tooltip. The tooltiptext class holds the actual tooltip text. It is hidden by default, and will be visible on hover. The :hover selector is used to show the tooltip text when the user moves the mouse over the <div> with class="tooltip". Positioning the Tooltip You can position the tooltip as you like. Here we will show how to position the tooltip to the left, right, top and bottom. Right- and Left-aligned Tooltip In this example, the tooltip is placed to the right (left:105%) of the "hoverable" text (<div>). Also note that top:-5px is used to place it in the middle of its container element. We use the number 5 because the tooltip text has a top and bottom padding of 5px. If you increase its padding, also increase the value of the top property to ensure that it stays in the middle (if this is something you want). The same applies if you want the tooltip placed to the left. Example Right-aligned tooltip: .tooltiptext { top: -5px; left: 105%; } Result: Hover over me Tooltip text Try it Yourself » Example Left-aligned tooltip: .tooltiptext { top: -5px; right: 105%; } Result: Hover over me Tooltip text Try it Yourself » Top- and Bottom-aligned Tooltip If you want the tooltip to appear on top or on the bottom, see examples below. Note that we use the margin-left property with a value of minus 65 pixels. This is to center the tooltip above/below the hoverable text. It is set to the half of the tooltip's width (130/2 = 65). Example Top-aligned tooltip: .tooltiptext { width: 130px; bottom: 100%; left: 65%; margin-left: -65px; /* Use half of the width (130/2 = 65), to center the tooltip */ } Result: Hover over me Tooltip text Try it Yourself » Example Bottom-aligned tooltip: .tooltiptext { width: 130px; top: 100%; left: 50%; margin-left: -65px; /* Use half of the width (130/2 = 65), to center the tooltip */ } Result: Hover over me Tooltip text Try it Yourself » Fade-in Tooltip If you want a tooltip that fades in, use the CSS transition property and the opacity property, and go from being completely invisible to 100% visible, in a number of specified seconds (2 second in our example): Example .tooltiptext { opacity: 0; transition: opacity 2s; } .tooltip:hover .tooltiptext { opacity: 1; } Try it Yourself » Tooltip Subpages Continue learning about CSS tooltips: Tooltip Arrows - arrow styling, fade-in effects ★ +1 Sign in to track progress
-
CSS Animations
CSS Animations CSS Animations CSS allows animation of HTML elements without using JavaScript! CSS What are CSS Animations? An animation lets an element gradually change from one style to another. You can change as many CSS properties you want, as many times as you want. To use CSS animation, you must specify some keyframes for the animation. Keyframes hold what styles the element will have at certain times. CSS animation-name and animation-duration The animation-name property specifies a name for the animation. The animation-duration property defines how long an animation should take to complete. If this property is not specified, no animation will occur, because the default value is 0s (0 seconds). CSS @keyframes Rule When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current style to the new style at certain times. To get an animation to work, you must bind the animation to an element. The following example binds the "myAnimation" animation to the <div> element. The animation will last for 4 seconds, and it will gradually change the background-color of the <div> element from "red" to "yellow": Example /* The animation code */ @keyframes myAnimation { from {background-color: red;} to {background-color: yellow;} } /* The element to apply the animation to */ div { width: 100px; height: 100px; background-color: red; animation-name: myAnimation; animation-duration: 4s; } Try it Yourself » In the example above we have used the keywords "from" and "to" in the @keyframes rule, which represents 0% (start) and 100% (complete). It is also possible to use percent. By using percent, you can add as many style changes as you like. The following example will change the background-color of the <div> element when the animation is 25% complete, 50% complete, and again when the animation is 100% complete: Example @keyframes myAnimation { 0% {background-color: red;} 25% {background-color: yellow;} 50% {background-color: blue;} 100% {background-color: green;} } div { width: 100px; height: 100px; background-color: red; animation-name: myAnimation; animation-duration: 4s; } Try it Yourself » The following example will change both the background-color and the position of the <div> element when the animation is 25% complete, 50% complete, and again when the animation is 100% complete: Example @keyframes myAnimation { 0% {background-color:red; left:0px; top:0px;} 25% {background-color:yellow; left:200px; top:0px;} 50% {background-color:blue; left:200px; top:200px;} 75% {background-color:green; left:0px; top:200px;} 100% {background-color:red; left:0px; top:0px;} } div { width: 100px; height: 100px; position: relative; background-color: red; animation-name: myAnimation; animation-duration: 4s; } Try it Yourself » Animation Subpages Continue learning about CSS animations: Animation Timing - delay, iteration count, timing function Animation Properties - direction, fill mode, shorthand ★ +1 Sign in to track progress
-
CSS Transitions
CSS Transitions CSS Transitions CSS transitions allows you to change property values smoothly, over a given duration. Mouse over the element below to see a CSS transition effect: CSS The CSS transition Property To create a transition effect, you must specify the CSS property you want to add a transition to, and the duration of the transition. The CSS transition property is a shorthand property for: transition-property transition-duration transition-timing-function transition-delay CSS Transition Example The following example shows a 100px * 100px <div> element. The <div> element has specified a transition effect for the width property, with a duration of 2 seconds: Example div { width: 100px; height: 100px; background-color: red; transition: width 2s; } How to Trigger the Transition The transition is triggered when there is a change in the element's properties. This often happens within pseudo-classes (:hover, :active, :focus, or :checked). So, from the code above, the transition effect will start when the width property changes value. Now, we add a div:hover class that specifies a new value for the width property when a user mouses over the <div> element: Example div:hover { width: 300px; } Try it Yourself » Notice that when the cursor mouses out of the element, it will gradually change back to its original style. Change Multiple Property Values You can change multiple properties by separating them by commas. The following example adds a transition effect for the width, height, and background-color properties, with a duration of 2 seconds for the width, 4 seconds for the height, and 3 seconds for the background-color: Example Add a transition effect for the width, height, and background-color properties: div { transition: width 2s, height 4s, background-color 3s; } Try it Yourself » Transition Subpages Continue learning about CSS transitions: Transition Timing - speed curves, delay, shorthand CSS Transition Properties The following table lists all the CSS transition properties: Property Description transition A shorthand property for setting the four transition properties into a single property transition-delay Specifies a delay (in seconds) for the transition effect transition-duration Specifies how many seconds or milliseconds a transition effect takes to complete transition-property Specifies the name of the CSS property the transition effect is for transition-timing-function Specifies the speed curve of the transition effect ★ +1 Sign in to track progress
-
CSS 3D Transforms
CSS 3D Transforms CSS 3D Transforms The CSS transform property applies a 2D or 3D transformation to an element. This property allows you to rotate, scale, move, and skew elements. Mouse over the elements below to see the difference between a 2D and a 3D transformation: 2D rotate 3D rotate CSS 3D Transforms Functions With the CSS transform property you can use the following 3D transformation functions: rotateX() rotateY() rotateZ() The CSS rotateX() Function The rotateX() function rotates an element around its X-axis at a given degree: Example #myDiv { transform: rotateX(150deg); } Try it Yourself » The CSS rotateY() Function The rotateY() function rotates an element around its Y-axis at a given degree: Example #myDiv { transform: rotateY(150deg); } Try it Yourself » The CSS rotateZ() Function The rotateZ() function rotates an element around its Z-axis at a given degree: Example #myDiv { transform: rotateZ(90deg); } Try it Yourself » CSS Transform Properties The following table lists all the 3D transform properties: Property Description transform Applies a 2D or 3D transformation to an element transform-origin Allows you to change the position on transformed elements transform-style Specifies how nested elements are rendered in 3D space perspective Specifies the perspective on how 3D elements are viewed perspective-origin Specifies the bottom position of 3D elements backface-visibility Defines whether or not an element should be visible when not facing the screen CSS 3D Transform Functions Function Description matrix3d() Defines a 3D transformation, using a 4x4 matrix of 16 values translate3d() Defines a 3D translation translateZ() Defines a 3D translation, using only the value for the Z-axis scale3d() Defines a 3D scale transformation scaleZ() Defines a 3D scale transformation by giving a value for the Z-axis rotate3d() Defines a 3D rotation rotateX() Defines a 3D rotation along the X-axis rotateY() Defines a 3D rotation along the Y-axis rotateZ() Defines a 3D rotation along the Z-axis perspective() Defines a perspective view for a 3D transformed element ★ +1 Sign in to track progress
-
CSS 2D Transforms
CSS 2D Transforms CSS 2D Transforms The CSS transform property applies a 2D or 3D transformation to an element. This property allows you to rotate, scale, move, and skew elements. Mouse over the element below to see a 2D transformation: 2D rotate CSS 2D Transforms Functions With the CSS transform property you can use the following 2D transformation functions: translate() rotate() scaleX() scaleY() scale() skewX() skewY() skew() matrix() The CSS translate() Function The translate() function moves an element from its current position (according to the parameters given for the X-axis and the Y-axis). The following example moves the <div> element 50 pixels to the right, and 100 pixels down from its current position: Example div { transform: translate(50px, 100px); } Try it Yourself » The CSS rotate() Function The rotate() function rotates an element clockwise or counter-clockwise according to a given degree. The following example rotates the <div> element clockwise with 20 degrees: Example div { transform: rotate(20deg); } Try it Yourself » Using negative values will rotate the element counter-clockwise. The following example rotates the <div> element counter-clockwise with 20 degrees: Example div { transform: rotate(-20deg); } Try it Yourself » Transform Subpages Continue learning about CSS 2D transforms: Scale Functions - scale(), scaleX(), scaleY() Skew and Matrix - skew(), skewX(), skewY(), matrix() CSS Transform Properties The following table lists all the 2D transform properties: Property Description transform Applies a 2D or 3D transformation to an element transform-origin Allows you to change the position on transformed elements CSS 2D Transform Functions Function Description matrix() Defines a 2D transformation, using a matrix of six values translate() Defines a 2D translation, moving the element along the X- and the Y-axis translateX() Defines a 2D translation, moving the element along the X-axis translateY() Defines a 2D translation, moving the element along the Y-axis scale() Defines a 2D scale transformation, scaling the elements width and height scaleX() Defines a 2D scale transformation, scaling the element's width scaleY() Defines a 2D scale transformation, scaling the element's height rotate() Defines a 2D rotation, the angle is specified in the parameter skew() Defines a 2D skew transformation along the X- and the Y-axis skewX() Defines a 2D skew transformation along the X-axis skewY() Defines a 2D skew transformation along the Y-axis ★ +1 Sign in to track progress
-
CSS Custom Fonts
CSS Custom Fonts The CSS @font-face Rule The CSS @font-face rule allows you to define and load custom fonts for use on a webpage. The font does not have to be installed on the user's computer. When you have found/bought the font you want to use, just include the font file on your web server, and it will be automatically downloaded to the user when needed. Common Font Formats The most widely used font formats are WOFF/WOFF2 for web pages and TTF/OTF for desktop. WOFF/WOFF2 (Web Open Font Format) WOFF/WOFF2 are optimized to reduce file size and are the ideal font format for use in web pages. It was developed in 2009, and is now a W3C Recommendation. WOFF/WOFF2 are supported by all major browsers. TTF (TrueType Fonts) and OTF (OpenType Fonts) TTF was developed in the late 1980s, by Apple. OTF was developed by Apple and Microsoft. TTF is the most common font format for both the Mac OS and Microsoft Windows operating systems. OTF is built on TTF, as a more advanced, scalable format that supports rich typesetting features. Both types are popular because of their accessibility and quality, but they are not optimized for web use. Use Your Custom Font In the @font-face rule; first specify a name for the custom font (e.g. "myFont") in the font-family descriptor, then point to the font file in the src descriptor. Then, to use the custom font in an HTML element, refer to the name of the font ("myFont") through the font-family property: Example @font-face { font-family: myFont; /* set name */ src: url(sansation_light.woff); /* url of the font */ } p { font-family: myFont; /* use font */ } Try it Yourself » Bold Custom Font You must add another @font-face rule containing descriptors for bold text: Example @font-face { font-family: myFont; src: url(sansation_bold.woff); font-weight: bold; } Try it Yourself » The file "sansation_bold.woff" is another font file, that contains the bold characters for the Sansation font. Browsers will use this file whenever a piece of text with the font-family "myFont" should render as bold. Tip: This way you can have many @font-face rules for the same font. CSS @font-face Descriptors The following table lists the font descriptors that can be defined inside the @font-face rule: Descriptor Description font-family Required. Defines a name for the font src Required. Defines the URL of the font file font-stretch Optional. Defines how the font should be stretched. Default is "normal" font-style Optional. Defines how the font should be styled. Default is "normal" font-weight Optional. Defines the weight of the font. Default is "normal" font-display Optional. Defines how the font loads and displays. Default is "auto" unicode-range Optional. Defines the range of UNICODE characters the font supports. Default is "U+0-10FFFF" ★ +1 Sign in to track progress
-
CSS Shadow Effects
CSS Shadow Effects Shadows With CSS you can create shadow effects! Hover over me! CSS Text Shadow The CSS text-shadow property applies a shadow to text. In its simplest use, you only specify the horizontal and the vertical shadow. In addition, you can add a shadow color and blur effect. Text shadow effect! Example Horizontal and vertical shadow: h1 { text-shadow: 2px 2px; } Try it Yourself » Next, add a color to the shadow: Text shadow effect! Example Horizontal and vertical shadow, with color: h1 { text-shadow: 2px 2px red; } Try it Yourself » Then, add a blur effect to the shadow: Text shadow effect! Example Horizontal and vertical shadow, with color and blur effect: h1 { text-shadow: 2px 2px 5px red; } Try it Yourself » The following example shows a white text with black shadow: Text shadow effect! Example Text-shadow on a white text: h1 { color: white; text-shadow: 2px 2px 4px #000000; } Try it Yourself » The following example shows a red neon glow shadow: Text shadow effect! Example Text-shadow with red neon glow: h1 { text-shadow: 0 0 3px #ff0000; } Try it Yourself » Multiple Shadows To add more than one shadow to the text, you can add a comma-separated list of shadows. The following example shows a red and blue neon glow shadow: Text shadow effect! Example h1 { text-shadow: 0 0 3px #ff0000, 0 0 5px #0000ff; } Try it Yourself » The following example shows a white text with black, blue, and darkblue shadow: Text shadow effect! Example h1 { color: white; text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue; } Try it Yourself » You can also use the text-shadow property to create a plain border around some text (without shadows): Border around text! Example h1 { color: coral; text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black; } Try it Yourself » ★ +1 Sign in to track progress
-
CSS Gradients
CSS Gradients CSS Gradients The CSS gradient functions let you display smooth transitions between two or more colors within an element. CSS defines three types of gradients: Linear Gradients - The color transition goes down, up, left, right, or diagonally Radial Gradients - The color transition goes out from a central point Conic Gradients - The color transition is rotated around a center point The CSS gradient functions are used within the background-image property. A Linear Gradient Background CSS linear-gradient() Function The CSS linear-gradient() function creates a linear gradient. A linear gradient defines a color transition that goes in a straight line, it can go down, up, to left, to right, or diagonally. A linear gradient requires at least two color stops. Color stops are the colors you want to render smooth transitions among. You can also set a starting point and a direction (or an angle) along with the gradient effect. Syntax background-image: linear-gradient(direction, color-stop1, color-stop2, ...); Direction - Top to Bottom (this is default) The following example shows a linear gradient that goes from top to bottom. It starts red, transitioning to yellow: top to bottom (default) Example #grad { background-image: linear-gradient(to bottom, red, yellow); } Try it Yourself » Direction - Bottom to Top The following example shows a linear gradient that goes from bottom to top. It starts red, transitioning to yellow: bottom to top Example #grad { background-image: linear-gradient(to top, red, yellow); } Try it Yourself » Direction - Left to Right The following example shows a linear gradient that goes from left to right. It starts red, transitioning to yellow: left to right Example #grad { background-image: linear-gradient(to right, red , yellow); } Try it Yourself » Direction - Diagonal The following example shows a linear gradient that goes from top-left to bottom-right. It starts red, transitioning to yellow: top left to bottom right Example #grad { background-image: linear-gradient(to bottom right, red, yellow); } Try it Yourself » Linear Gradient - Using Angles If you want more control over the direction of the gradient, you can define an angle parameter, instead of the predefined directions (to bottom, to top, to right, to left, to bottom right, etc.). A value of 0deg is equivalent to "to top". A value of 90deg is equivalent to "to right". A value of 180deg is equivalent to "to bottom". A value of 270deg equivalent to "to left" Syntax background-image: linear-gradient(angle, color-stop1, color-stop2); The following example shows how to use angles on linear gradients: 180deg Example #grad { background-image: linear-gradient(180deg, red, yellow); } Try it Yourself » Linear Gradient - Multiple Color Stops The following example shows a linear gradient (from top to bottom) with multiple color stops: Example #grad { background-image: linear-gradient(red, yellow, green); } Try it Yourself » The following example shows a linear gradient (from left to right) with the color of the rainbow and some text: Rainbow Background Example #grad { background-image: linear-gradient(to right, red,orange,yellow,green,blue,indigo,violet); } Try it Yourself » Linear Gradient - Transparency CSS gradients also support transparency, which can be used to create fading effects. To add transparency, we use the rgba() function to define the color stops. The last parameter in the rgba() function can be a value from 0 to 1, and it defines the transparency of the color: 0 indicates full transparency, 1 indicates full color (no transparency). The following example shows a linear gradient that goes from left to right. It starts fully transparent, transitioning to full color red: Example #grad { background-image: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1)); } Try it Yourself » CSS repeating-linear-gradient() Function The CSS repeating-linear-gradient() function is used to repeat linear gradients: Example A repeating linear gradient: #grad { background-image: repeating-linear-gradient(red, yellow 10%, green 20%); } Try it Yourself » ★ +1 Sign in to track progress
-
CSS Colors
CSS Colors CSS supports 140+ color names, HEX values, RGB values, RGBA values, HSL values, HSLA values, and opacity. RGBA Colors RGBA color values are an extension of RGB colors with an alpha channel - which specifies the opacity for a color. An RGBA color value is specified with: rgba(red, green, blue, alpha) The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque). rgba(255, 0, 0, 0.2); rgba(255, 0, 0, 0.4); rgba(255, 0, 0, 0.6); rgba(255, 0, 0, 0.8); The following example defines different RGBA colors: Example #p1 {background-color: rgba(255, 0, 0, 0.3);} /* red with opacity */ #p2 {background-color: rgba(0, 255, 0, 0.3);} /* green with opacity */ #p3 {background-color: rgba(0, 0, 255, 0.3);} /* blue with opacity */ Try it Yourself » HSLA Colors HSLA color values are an extension of HSL colors with an alpha channel - which specifies the opacity for a color. An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha) The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque): hsla(0, 100%, 30%, 0.3); hsla(0, 100%, 50%, 0.3); hsla(0, 100%, 70%, 0.3); hsla(0, 100%, 90%, 0.3); The following example defines different HSLA colors: Example #p1 {background-color: hsla(120, 100%, 50%, 0.3);} /* green with opacity */ #p2 {background-color: hsla(120, 100%, 75%, 0.3);} /* light green with opacity */ #p3 {background-color: hsla(120, 100%, 25%, 0.3);} /* dark green with opacity */ #p4 {background-color: hsla(120, 60%, 70%, 0.3);} /* pastel green with opacity */ Try it Yourself » CSS opacity Property The opacity property sets the opacity for the whole element (both background color and text will be opaque/transparent). The opacity property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque). rgb(255, 0, 0);opacity:0.2; rgb(255, 0, 0);opacity:0.4; rgb(255, 0, 0);opacity:0.6; rgb(255, 0, 0);opacity:0.8; Notice that the text inside the element will also be transparent/opaque! The following example shows different elements with opacity: Example #p1 {background-color:rgb(255,0,0);opacity:0.6;} /* red with opacity */ #p2 {background-color:rgb(0,255,0);opacity:0.6;} /* green with opacity */ #p3 {background-color:rgb(0,0,255);opacity:0.6;} /* blue with opacity */ Try it Yourself » ★ +1 Sign in to track progress
-
CSS Multiple Backgrounds
CSS Multiple Backgrounds CSS Multiple Backgrounds CSS allows you to add multiple background images for an element, through the background-image property. The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer. The following example has two background images, the first image is a flower (aligned to the right-bottom) and the second image is a paper-like background (aligned to the top-left corner): Lorem Ipsum Dolor Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Example #example1 { background-image: url(img_flwr.gif), url(paper.gif); background-position: right bottom, left top; background-repeat: no-repeat, repeat; } Try it Yourself » Multiple background images can be specified using either the individual background properties (as above) or with the background shorthand property. The following example uses the background shorthand property (same result as example above): Example #example1 { background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat; } Try it Yourself » CSS Advanced Background Properties Property Description background A shorthand property for setting all the background properties in one declaration background-clip Specifies the painting area of the background background-image Specifies one or more background images for an element background-origin Specifies where the background image(s) is/are positioned background-size Specifies the size of the background image(s) ★ +1 Sign in to track progress
-
CSS Border Images
CSS Border Images CSS Border Images With the CSS border-image property, you can define an image to be used as the border around an element. CSS border-image Property The border-image property allows you to define an image to be used as the border around an element, instead of the normal border. This property takes an image and slices it into nine sections, like a tic-tac-toe board. It then places the corners at the corners, and the middle sections are repeated or stretched as you specify. The border-image property is a shorthand property for the following properties: border-image-source - defines the path to the image border-image-slice - defines how to slice the image border-image-width - defines the width of the image border-image-outset defines the amount by which the border image area extends beyond the border box border-image-repeat - defines how to repeat the image Note: For border-image to work, the element also needs the border property set! CSS border-image Examples We will use the following image (named "border.png"): In the following example, the url(border.png) specifies the source image, the number 30 slices the image 30 pixels from each edge, and the round value specifies that the middle section of the image is tiled (repeated) to fill the area (and rescaled to fit, if needed): An image as the border! Here is the code: Example #borderimg { border: 10px solid transparent; /* Required for border-image */ padding: 15px; border-image: url(border.png) 30 round; } Try it Yourself » Here, the stretch value specifies that the middle section of the image is stretched to fill the area: An image as the border! Here is the code: Example #borderimg { border: 10px solid transparent; /* Required for border-image */ padding: 15px; border-image: url(border.png) 30 stretch; } Try it Yourself » CSS border-image - Different Slice Values Different slice values completely changes the look of the border image: Example 1: border-image: url(border.png) 50 round; Example 2: border-image: url(border.png) 20% round; Example 3: border-image: url(border.png) 30% round; Here is the code: Example #borderimg1 { border: 10px solid transparent; padding: 15px; border-image: url(border.png) 50 round; } #borderimg2 { border: 10px solid transparent; padding: 15px; border-image: url(border.png) 20% round; } #borderimg3 { border: 10px solid transparent; padding: 15px; border-image: url(border.png) 30% round; } Try it Yourself » CSS Border Image Properties Property Description border-image A shorthand property for setting all the border-image-* properties border-image-source Specifies the path to the image to be used as a border border-image-slice Specifies how to slice the border image border-image-width Specifies the widths of the border image border-image-outset Specifies the amount by which the border image area extends beyond the border box border-image-repeat Specifies whether the border image should be repeated, rounded or stretched ★ +1 Sign in to track progress
-
CSS Rounded Corners
CSS Rounded Corners CSS Rounded Corners The CSS border-radius property is used to create rounded corners for elements. CSS border-radius Property The border-radius property defines the radius of an element's corners. This property can be applied to all elements with a background-color, a border, or a background-image. Here are three examples: 1. Rounded corners for an element with a background color: Rounded corners! 2. Rounded corners for an element with a border: Rounded corners! 3. Rounded corners for an element with a background image: Rounded corners! Here is the code: Example #div1 { border-radius: 25px; background-color: #73AD21; padding: 20px; width: 200px; height: 150px; } #div2 { border-radius: 25px; border: 2px solid #73AD21; padding: 20px; width: 200px; height: 150px; } #div3 { border-radius: 25px; background-image: url(paper.gif); background-position: left top; background-repeat: repeat; padding: 20px; width: 200px; height: 150px; } Try it Yourself » Tip: The border-radius property is actually a shorthand property for the border-top-left-radius, border-top-right-radius, border-bottom-right-radius and border-bottom-left-radius properties. CSS border-radius - Specify Each Corner The border-radius property can have from one to four values. Here are the rules: Four values - border-radius: 15px 50px 30px 5px; (first value applies to top-left corner, second value applies to top-right corner, third value applies to bottom-right corner, and fourth value applies to bottom-left corner): Three values - border-radius: 15px 50px 30px; (first value applies to top-left corner, second value applies to top-right and bottom-left corners, and third value applies to bottom-right corner): Two values - border-radius: 15px 50px; (first value applies to top-left and bottom-right corners, and the second value applies to top-right and bottom-left corners): One value - border-radius: 15px; (the value applies to all four corners, which are rounded equally: Here is the code: Example #div1 { border-radius: 15px 50px 30px 5px; /* four values */ background: #04AA6D; width: 200px; height: 150px; } #div2 { border-radius: 15px 50px 30px; /* three values */ background: #04AA6D; width: 200px; height: 150px; } #div3 { border-radius: 15px 50px; /* two values */ background: #04AA6D; width: 200px; height: 150px; } #div4 { border-radius: 15px; /* one value */ background: #04AA6D; width: 200px; height: 150px; } Try it Yourself » CSS Elliptical and Circular Shapes To create elliptical corners, you must specify two values for each radius, separated by a slash /. The first value defines the horizontal radius, and the second value defines the vertical radius. To create a oval shape (for a rectangular element), or to create a circular shape (for a square element) set border-radius to 50%. Example Create elliptical, oval and circular shapes: #div1 { border-radius: 70px / 30px; background: #04AA6D; width: 200px; height: 150px; } #div2 { border-radius: 15px / 50px; background: #04AA6D; width: 200px; height: 150px; } #div3 { border-radius: 50%; background: #04AA6D; width: 200px; height: 150px; } #div4 { border-radius: 50%; background: #04AA6D; width: 200px; height: 200px; } Try it Yourself » CSS Rounded Corners Properties Property Description border-radius A shorthand property for setting all the four border-*-*-radius properties border-top-left-radius Defines the shape of the border of the top-left corner border-top-right-radius Defines the shape of the border of the top-right corner border-bottom-right-radius Defines the shape of the border of the bottom-right corner border-bottom-left-radius Defines the shape of the border of the bottom-left corner ★ +1 Sign in to track progress
-
CSS Website Layout
CSS Website Layout CSS Website Layout A website is often divided into multiple sections, like a top header, navigation menu, main content, and a footer: Header Navigation Menu Content Main Content Content Footer There are tons of different layout designs to choose from. However, the structure above, is one of the most common, and we will take a closer look at it in this tutorial. CSS Header A header is usually located at the top of the website, and often contains a logo or the website name: Example header { background-color: #f1f1f1; text-align: center; padding: 10px; } Result My Header Try it Yourself » CSS Navigation Bar A navigation bar contains a list of links to help visitors navigate through your website: Example /* Style the topnav */ ul.topnav { display: flex; list-style-type: none; margin: 0; padding: 0; background-color: #333333; } /* Style links in topnav */ ul.topnav li a { display: block; color: #f1f1f1; padding: 14px 16px; text-decoration: none; } /* Change color on hover */ ul.topnav li a:hover { background-color: #dddddd; color: black; } Result Link1 Link2 Link3 Link4 Try it Yourself » CSS Layout Content How the content of a website should be shown, often depends on the device of the users. The most common layouts are: 1-column layout (often used for mobile browsers) 2-columns layout (often used for tablets and laptops) 3-columns layout (only used for desktops) 1-column: 2-column: 3-column: Here we will create a 3-column layout, and change it to a 1-column layout when the width of the screen is less than 600px: Example div.flex-container { display: flex; /* Show the flex items horizontally */ flex-direction: row; } div.flex-container > div { margin: 10px; } /* Use media query and show the flex items vertically if screen width is less than 600px */ @media screen and (max-width:600px) { div.flex-container { flex-direction: column; } } Result ColumnLorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. ColumnLorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. ColumnLorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Try it Yourself » Tip: Learn more about the CSS @media rule in our CSS Media Queries chapter. Tip: Learn more about CSS Flexbox in our CSS Flexbox chapter. CSS Basic and Fixed Footer The footer is placed at the bottom of a webpage. It often contains information like copyright and contact info. The following example shows a basic footer styling: Example footer { background-color: #f1f1f1; text-align: center; padding: 8px; } Result Footer Try it Yourself » The following example shows a fixed footer that is always visible at the bottom of the page, regardless of scrolling: Example footer { position: fixed; bottom: 0; left: 0; width: 100%; background-color: #f1f1f1; padding: 8px; text-align: center; z-index: 1000; } Try it Yourself » CSS Responsive Website In this example, we use media queries together with flexbox to create a responsive website, containing a flexible navigation bar and flexible content. Example Try it Yourself » Ever heard about W3Schools Spaces? Here you can create your website from scratch or use a template. Get started for free ❯ * no credit card required ★ +1 Sign in to track progress
-
CSS Accessibility Styling
CSS Accessibility Styling CSS Accessibility Styling A website should be designed to ensure good accessibility for all users, including those with disabilities. CSS accessibility styling is about using good styling technics to improve the visual clarity, navigation, and overall user experience. CSS Accessibility Styling Technics Here are some tips and technics on how to improve the accessibility of your web site: 1. Provide High Color Contrast Always use a good color contrast between the text and the background for readability. This is especially important for users with visual impairments or color blindness. Good Color Contrast body { background-color: #ffffff; color: #000000; } Try it Yourself » Bad Color Contrast body { background-color: #eeeeee; color: #cccccc; } Try it Yourself » 2. Provide Good Font, Font Size and Line Height Always provide a font that is easily readable. In addition, use a proper font size and line height. Use relative units (like rem) for font-size, to allow the user to scale the text size in the browser settings. Good Font Example body { font-family: Arial, sans-serif; font-size: 1rem; line-height: 1.6; } Try it Yourself » Bad Font Example body { font-family: Georgia, serif; font-size: 12px; font-style: italic; font-variant: small-caps; line-height: 90%; } Try it Yourself » 3. Have Visible Focus Indicators Always use the :focus pseudo-class to ensure that interactive elements (like links, buttons, input fields) have a clear visual focus style. Using :focus will ensure that keyboard users and screen-readers understand which element is currently active. Example a:focus, button:focus, input:focus { outline: 2px solid orange; } Try it Yourself » 4. Avoid Hiding Focus Never remove the default focus outlines, without replacing them with another visible focus style. Bad Example button:focus { outline: none; } Try it Yourself » Good Example button:focus { outline: 2px solid orange; } Try it Yourself » 5. Use CSS + Semantic HTML Use CSS for visual styling, and structure content with semantic HTML elements (instead of non-semantic elements, like <div> for everything). Example nav { background-color: #333333; color: white; } aside { background-color: #333333; color: white; } 6. Respect User Preferences The CSS prefers-reduced-motion @media feature lets you check if a user has asked to reduce motion, such as animations or transitions. Some users have motion sensitivity and prefer websites with less animation. You can use this media query to turn off, or tone down animations and transitions for the users who has activated this setting on their computer: Example @media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } } Try it Yourself » You will learn more about media queries in a later chapter. Summary Provide high color contrast Provide easily readable fonts Keep focus outlines visible Use semantic HTML elements Respect user preferences ★ +1 Sign in to track progress
-
CSS Performance Optimization
CSS Performance Optimization Optimizing CSS Optimizing CSS makes your website load faster and run more smoothly; which also results in a better user experience. Here are some tips for optimizing CSS: 1. Use Simple Selectors Use simple selectors when possible. Complex selectors increase the parsing time. Bad Example body #navlist ul li a.button:hover { background-color: blue; } Better Example .button:hover { background-color: blue; } 2. Avoid Universal Selector for Styling Avoid the universal selector (*) when not strictly necessary. The universal selector (*) affects every element and can slow down page rendering. Example * { margin: 0; padding: 0; font-size: 16px; } 3. Avoid Inline Styles Avoid inline styles when not necessary. Inline styles make your HTML heavier and are harder to manage. Bad Example <div style="color: red; font-size: 18px;">Hello</div> <p style="color: blue; font-size: 16px;">Test</p> 4. Avoid @import Avoid using @import for loading external CSS, as it delays stylesheet loading. Add external CSS with the <link> tag in the head section, so it loads before the page is rendered. Example <link rel="stylesheet" href="style.css"> 5. Use Shorthand Properties Use shorthand properties when possible. It saves space and is faster to parse. Example /* Long version */ margin-top: 10px; margin-right: 20px; margin-bottom: 10px; margin-left: 20px; /* Shorthand version */ margin: 10px 20px; 6. Cut Down Unnecessary Animations A high number of animations and large animations require more processing power to handle, which degrades performance. So, remove unnecessary animations. 7. Use Properties that Not Cause Repaint of Animations Animation performance relies also on what properties you are animating. Some properties (like width, height, left, top), trigger a layout recalculation when animated, and should be avoided. If possible, use animation properties that do not cause repaint, like transforms, opacity and filter. 8. Combine and Minify CSS Use one CSS file when possible, and remove spaces and comments to reduce file size. You can use tools like: CSS Minifier PostCSS Online compressors 9. Cache Your CSS Make sure your CSS file is cached by the browser by giving it a long expiration time in your server settings. This reduces how often users need to re-load it. Summary Keep selectors short and simple Avoid layout-thrashing operations Use efficient animation techniques Use external, minified, and cached stylesheets ★ +1 Sign in to track progress
-
CSS Math Functions
CSS Math Functions CSS Math Functions CSS math functions allow mathematical expressions to be used as property values. In this chapter, we will explain the following math functions: calc() max() min() clamp() The CSS calc() Function The calc() function performs a mathematical calculation that will be used as the property value. The calc() function supports addition (+), subtraction (-), multiplication (*), and division (/), and can combine different units, like pixels and percentages. CSS Syntax calc(expression) Value Description expression Required. A mathematical expression. The result will be used as the value Let us look at an example: Example Use calc() to calculate the width and the height of a <div> element: #div1 { margin: auto; width: calc(100% - 100px); height: calc(30vh + 50px); border: 1px solid black; padding: 10px; } Try it Yourself » The CSS max() Function The max() function takes a comma-separated list of values, and uses the largest value from the list as the property value. CSS Syntax max(value1, value2, ...) Value Description value1, value2, ... Required. A list of comma-separated values Let us look at an example: Example Use max() to set the width of #div1 to whichever value is largest, 50% or 300px: #div1 { height: 100px; width: max(50%, 300px); border: 1px solid black; padding: 10px; } Try it Yourself » The CSS min() Function The min() function takes a comma-separated list of values, and uses the smallest value from the list as the property value. CSS Syntax min(value1, value2, ...) Value Description value1, value2, ... Required. A list of comma-separated values Let us look at an example: Example Use min() to set the width of #div1 to whichever value is smallest, 50% or 300px: #div1 { height: 100px; width: min(50%, 300px); border: 1px solid black; padding: 10px; } Try it Yourself » The CSS clamp() Function The clamp() function is used to set a value that will adjust responsively between a minimum value and a maximum value depending on the size of the viewport. The clamp() function has three parameters: a minimum value, a preferred value, and a maximum value. If the preferred value is smaller than the minimum value or larger than the maximum value, the preferred value is used. CSS Syntax clamp(min, preferred, max) Value Description min Optional. Specifies the smallest allowed value preferred Required. Specifies the preferred value max Optional. Specifies the largest allowed value Let us look at an example: Example Set the <h2> element's minimum font-size to 2rem, and the maximum font-size to 3.5rem. Also, set the <p> element's minimum font-size to 1rem, and the maximum font-size to 2.5rem: h2 { font-size: clamp(2rem, 2.5vw, 3.5rem); } p { font-size: clamp(1rem, 2.5vw, 2.5rem); } Try it Yourself » CSS Functions Reference For a complete list of all CSS functions, visit our CSS Functions Reference. ★ +1 Sign in to track progress
-
CSS The !important Rule
CSS The !important Rule CSS !important Rule The !important rule is used to give the value of a specific property the highest priority. The !important rule will override ALL previous styling rules for that specific property on that element! The !important keyword is added to the end of a CSS declaration, before the semicolon. Syntax selector { property: value !important; } CSS !important Rule Example In the following example, all three paragraphs will get a yellow background color, even though the inline style, id selector, and the class selector have a higher specificity. The !important rule overrides ALL styling rules for that specific property on that element! Example Using the !important rule: <html> <head> <style> p { background-color: yellow !important; } #myid { background-color: blue; } .myclass { background-color: gray; } </style> </head> <body> <p style="background-color:orange;">This is a paragraph.</p> <p class="myclass">This is a paragraph.</p> <p id="myid">This is a paragraph.</p> </body> </html> Try it Yourself » Use !important Sparingly The only way to override an !important rule is to include another !important rule on a declaration with the same (or higher) specificity in the source code - and here the problem starts! The CSS code will be confusing and the debugging will be hard! Especially if you have a large style sheet! In the following example, it is not very clear which color is considered most important: Example p { background-color: red !important; } #myid { background-color: blue !important; } .myclass { background-color: gray !important; } Try it Yourself » A Few Fair Uses of !important The !important rule can be useful in some cases, like: 1. To override a style that cannot be overridden in any other way. This could be if you are working in a Content Management System (CMS) and cannot edit the CSS code. Then you can set some custom styles to override some of the CMS styles. 2. To respect user preferences. Some users have motion sensitivity and prefer websites with less animation. CSS has a @media feature called prefers-reduced-motion that lets you check if a user has asked to reduce motion, such as animations or transitions. You can use !important to turn off, or tone down animations and transitions for the users who has activated this setting on their computer: Example @media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } } Try it Yourself » You will learn more about media queries in a later chapter. 3. To create a highly specific, unchangeable style for a specific element. Assume we want a special look for all link buttons on a page: Example Style link buttons with a gray background color, white text, and some padding and border: a.button { background-color: #8c8c8c; color: white; padding: 5px; border: 1px solid black; text-decoration: none; } Try it Yourself » Now, if we put a link button inside another element with higher specificity, the properties might get in conflict. Here is an example of this: Example a.button { background-color: #8c8c8c; color: white; padding: 5px; border: 1px solid black; text-decoration: none; } #myDiv a { color: red; background-color: yellow; } Try it Yourself » To "force" all buttons to have the same look, no matter what, we can add the !important rule to the properties of the button, like this: Example a.button { background-color: #8c8c8c !important; color: white !important; padding: 5px !important; border: 1px solid black !important; text-decoration: none !important; } #myDiv a { color: red; background-color: yellow; } Try it Yourself » ★ +1 Sign in to track progress
-
CSS Inheritance
CSS Inheritance CSS Inheritance CSS inheritance is about what happens if no value is specified for a property on an element. If no value is specified for a property, the value can either be inherited from the parent element, or be set to its initial (default) value. For CSS inheritance, properties are categorized in two types: inherited properties non-inherited properties Inherited Properties Inherited properties are, by default, set to the computed value of the parent element. Properties related to text, such as color, font-family, font-size, line-height, and text-align, are typically inherited. This ensures consistent text styling throughout a document. In the following example, the text inside the <strong> element will appear in 20px and in blue, since the <strong> element inherits the color and the font-size value from the parent (<p>) element. Example The color and font-size properties are inherited: <style> p { color: blue; font-size: 20px; } </style> <body> <p>This is a paragraph with some <strong>important</strong> text.</p> </body> Try it Yourself » Non-inherited Properties If there is not set a value for a non-inherited property, the value is set to the initial (default) value of that property. Properties related to the box model or layout, like border, background, margin, padding, width, and height, are typically not inherited. In the following example, the <strong> element, inside the <p> element, will not have an additional border (since the initial value of border-style is none). Example The border property is not inherited: <style> p { border: 1px solid red; } </style> <body> <p>This is a paragraph with some <strong>important</strong> text.</p> </body> Try it Yourself » The inherit Keyword The inherit keyword is used to explicitly specify inheritance. It works on both inherited and non-inherited properties. In the following example, the <strong> element, inside the <p> element, will have an additional border, since we have used the inherit keyword to explicitly specify that the border value should be inherit. Example Explicitly set the inheritance with the inherit keyword: <style> p { border: 1px solid red; } strong { border: inherit; } </style> <body> <p>This is a paragraph with some <strong>strong</strong> text.</p> </body> Try it Yourself » ★ +1 Sign in to track progress
-
CSS Units
CSS Units CSS Units CSS has several different units for expressing a length. Many CSS properties take "length" values, such as width, margin, padding, font-size, etc. Example Set different length values with px and em: h1 { font-size: 60px; } p { font-size: 1.5em; line-height: 2em; } Try it Yourself » The length value is a number followed by a length unit, such as px, em, rem, etc. Note: A whitespace cannot appear between the number and the unit. However, if the value is 0, the unit can be omitted. Two Types of Length Units CSS has two types of length units: Absolute units - Fixed sizes that do not change Relative units - Sizes relative to another length (parent, root, or viewport) Absolute Units Absolute units are fixed, and the length expressed in any of these will appear exactly that size. The most used absolute unit is px (pixels). Absolute units are not recommended for screens, because screen sizes vary so much. However, they can be used if the output medium is known, such as for print layout. Unit Description px pixels (1px = 1/96th of 1in) pt points (1pt = 1/72 of 1in) cm, mm, in, pc centimeters, millimeters, inches, picas Learn more about Absolute Units » Relative Units Relative units specify a length relative to another length (like parent element, root element, or viewport). Relative length units scale better between different screen sizes, making them ideal for responsive web design. Unit Description em Relative to the font-size of the parent element rem Relative to the font-size of the root element vw, vh Relative to 1% of the viewport width/height % Relative to the size of the parent element Tip: The em and rem units are perfect for creating scalable and responsive websites! Learn more about Relative Units » ★ +1 Sign in to track progress
-
CSS Counters
CSS Counters CSS Counters With CSS counters, you can create dynamic numbering of elements (like headings, sections, or list items) without using JavaScript. CSS counters are "variables" maintained by CSS, and their values can be incremented (or decremented) by CSS rules. Pizza Hamburger Hotdogs CSS Automatic Numbering With Counters CSS counters are like "variables". The variable values can be incremented (or decremented) by CSS rules. To work with CSS counters we will use the following properties: counter-reset - Creates or resets a counter counter-increment - Increments or decrements a counter content - Inserts generated content counter() - Adds the value of a counter to an element To use a CSS counter, it must first be created with the counter-reset property. CSS Increase and Decrease Counter The following example creates a counter for the page (in the body selector), then it increments the counter value by 1 for each <h2> element: Example body { counter-reset: section; } h2::before { counter-increment: section; content: "Section " counter(section) ": "; } Try it Yourself » Decrementing a Counter The counter-increment property has a second parameter. The default value is 1. To decrease the counter value, you can set it to -1. Example body { counter-reset: section; } h2::before { counter-increment: section -1; content: "Section " counter(section) ": "; } Try it Yourself » Incrementing by Custom Values You can increment the counter by any value. Here we increment by 2: Example body { counter-reset: section; } h2::before { counter-increment: section 2; content: "Section " counter(section) ": "; } Try it Yourself » ★ +1 Sign in to track progress
-
CSS Forms
CSS Forms CSS Styling Forms CSS is used to style HTML forms. The look of an HTML form can be greatly improved with CSS: Styling Form Input Fields With CSS, you can style most of the different input types, like text fields, password fields, checkboxes, radio buttons, and file inputs. You can also style input labels and form buttons. Some commonly used CSS properties for styling input fields, are: width padding margin border border-radius background-color color font-size ★ +1 Sign in to track progress