所有动态
- 一小时前
-
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
-
CSS Attribute Selectors
CSS Attribute Selectors CSS Attribute Selectors CSS attribute selectors are used to select and style HTML elements with a specific attribute or attribute value, or both. Example Select all <a> elements with a target attribute: a[target] { background-color: yellow; } Try it Yourself » Basic Attribute Selectors Basic attribute selectors match elements that have a specific attribute or a specific attribute value. CSS [attribute] Selector The [attribute] selector is used to select elements with a specific attribute. The following example selects all <a> elements with a target attribute: Example a[target] { background-color: yellow; } Try it Yourself » CSS [attribute="value"] Selector The [attribute="value"] selector is used to select elements with a specific attribute with an exact value. The following example selects all <a> elements with a target="_blank" attribute: Example a[target="_blank"] { background-color: yellow; } Try it Yourself » CSS [attribute~="value"] Selector The [attribute~="value"] selector is used to select elements with an attribute value containing a specific word. The following example selects all elements with a title attribute that contains a space-separated list of words, one of which is "flower": Example [title~="flower"] { border: 5px solid yellow; } Try it Yourself » The example above will match elements with title="flower", title="summer flower", and title="flower new", but not title="my-flower" or title="flowers". CSS [attribute|="value"] Selector The [attribute|="value"] selector is used to select elements with the specific attribute, whose value can be exactly the specific value, or start with the specific value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen ( - ), like class="top-text". Example [class|="top"] { background: yellow; } Try it Yourself » ★ +1 Sign in to track progress
-
CSS Image Sprites
CSS Image Sprites CSS Image Sprites An image sprite is a collection of various small images put into one larger image file, called a "sprite image". A sprite image is typically arranged in a grid-like way, like this: A web page with multiple images takes a longer time to load, and generates multiple server requests. So, instead of downloading each image separately, the browser downloads the single sprite image file, which will reduce the number of server requests and reduce bandwidth usage. CSS Image Sprites Example The CSS key properties used for image sprites are: background-image background-position Here, the CSS code specifies which part of the sprite image ("img_navsprites.gif") to show for the different navigation items (home, next, and previous): Example <html> <head> <style> #home { width: 46px; height: 44px; background-image: url(img_navsprites.gif); background-position: 0 0; /* Top-left corner of the sprite */ } #prev { width: 43px; height: 44px; background-image: url('img_navsprites.gif'); background-position: -47px 0; /* 47px to the left of the sprite's top-left */ } #next { width: 43px; height: 44px; background-image: url('img_navsprites.gif'); background-position: -91px 0; /* 91px to the left of the sprite's top-left */ } </style> </head> <body> <img id="home" src="img_trans.gif" width="1" height="1"> <img id="prev" src="img_trans.gif" width="1" height="1"> <img id="next" src="img_trans.gif" width="1" height="1"> </body> </html> Try it Yourself » Example explained: width, height - Defines the width and height of each image-parts background-image: url(img_navsprites.gif); - Defines the url of the image sprite background-position - Shifts the background image within each element, to display only the desired portion of the sprite image <img id="home" src="img_trans.gif"> - Each image just start with a small transparent image because the src attribute cannot be empty (the displayed image will be the background image we specify in CSS) Image Sprites in a Navigation List Here, we use the sprite image ("img_navsprites.gif") inside a navigation list. We will use an HTML list (<ul> and <li>) for the navigation list: Example #navlist { position: relative; } #navlist li { margin: 0; padding: 0; list-style: none; position: absolute; top: 0; } #navlist li, #navlist a { height: 44px; display: block; } #home { left: 0px; width: 46px; background: url('img_navsprites.gif') 0 0; } #prev { left: 60px; width: 43px; background: url('img_navsprites.gif') -47px 0; } #next { left: 120px; width: 43px; background: url('img_navsprites.gif') -91px 0; } Try it Yourself » Example explained: #navlist {position:relative;} - position is set to relative to allow absolute positioning inside it #navlist li - set margin and padding to 0, remove bullets, and all <li> are absolute positioned #navlist li, #navlist a - set the height of all images to 44px and display as block Now position and style each navigation item: #home {left:0px;width:46px;} - Positioned all the way to the left, and the width of the image is 46px #home {background:url(img_navsprites.gif) 0 0;} - Defines the background image and its position (left 0px, top 0px) #prev {left:60px;} - Positioned 60px to the right (#home width 46px + some extra space between items) #prev {background:url('img_navsprites.gif') -47px 0;} - Defines the background image 47px to the right (#home width 46px + 1px line divider) #next {left:120px;} - Positioned 120px to the right (start of #prev is 60px + #prev width 43px + extra space) #next {background:url('img_navsprites.gif') -91px 0;} - Defines the background image 91px to the right (#home width 46px + 1px line divider + #prev width 43px + 1px line divider) Image Sprites - Hover Effect Now we want to add a hover effect to our navigation list. Our new image ("img_navsprites_hover.gif") contains three navigation images and three images to use for hover effects: Because this is one single image, and not six separate files, there will be no loading delay when a user hovers over the image. We only add three lines of code to add the hover effect: Example #home a:hover { background: url('img_navsprites_hover.gif') 0 -45px; } #prev a:hover { background: url('img_navsprites_hover.gif') -47px -45px; } #next a:hover { background: url('img_navsprites_hover.gif') -91px -45px; } Try it Yourself » Example explained: #home a:hover {background: url('img_navsprites_hover.gif') 0 -45px;} - For all three hover images we specify the same background position, only 45px further down ★ +1 Sign in to track progress
-
CSS Image Gallery
CSS Image Gallery CSS Image Gallery A CSS image gallery is a collection of images that is displayed in an organized, and often responsive way, on a web page. Here we use CSS to create an image gallery: Cinque Terre Green Forest Northern Lights Mountains The HTML structure for an image gallery is: A container element to wrap the entire gallery (like a <div> with class="gallery"). Another container element for each image (like a <div> with class="gallery-item"), that contains the <img> tag and possibly a description. Here is the HTML and CSS code: Example <html> <head> <style> div.gallery { display: flex; flex-wrap: wrap; justify-content: flex-start; } div.gallery-item { margin: 5px; border: 1px solid #ccc; width: 180px; } div.gallery-item:hover { border: 1px solid #777; } div.gallery-item img { width: 100%; height: auto; } div.gallery-item div.desc { padding: 15px; text-align: center; } </style> </head> <body> <div class="gallery"> <div class="gallery-item"> <a target="_blank" href="img_5terre.jpg"> <img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400"> </a> <div class="desc">Cinque Terre</div> </div> <div class="gallery-item"> <a target="_blank" href="img_forest.jpg"> <img src="img_forest.jpg" alt="Forest" width="600" height="400"> </a> <div class="desc">Green Forest</div> </div> <div class="gallery-item"> <a target="_blank" href="img_lights.jpg"> <img src="img_lights.jpg" alt="Northern Lights" width="600" height="400"> </a> <div class="desc">Northern Lights</div> </div> <div class="gallery-item"> <a target="_blank" href="img_mountains.jpg"> <img src="img_mountains.jpg" alt="Mountains" width="600" height="400"> </a> <div class="desc">Mountains</div> </div> </div> </body> </html> Try it Yourself » Tip: We have used display: flex; for the image gallery above. This layout module is effective for arranging images in rows or columns. You will learn more about CSS Flexbox later in our CSS Tutorial. CSS Responsive Image Gallery Here we use CSS media queries to re-arrange the images on different screen sizes: If screen is larger than 768px wide - show four images side by side If screen is smaller than 768px - show two images side by side If screens is smaller than 480px - stack the images vertically (width: 100%) Tip: You will learn more about media queries later in our CSS Tutorial. Example Try it Yourself » ★ +1 Sign in to track progress
-
CSS Dropdowns
CSS Dropdowns CSS Dropdowns CSS dropdowns are used to display a list of options or content when a user clicks or hover over an element, like a button or a navigation link. A CSS dropdown consists of a trigger element (like <div>, <button>, <p>, <a>, etc.). When the trigger element is clicked or hovered over, the dropdown content will be displayed. The dropdown content is a container element (e.g. <div>) that holds the hidden content (can be text, links, images, etc.). Mouse over the three CSS dropdown examples below: Dropdown Text Hello World! Dropdown Menu Link 1 Link 2 Link 3 Other: Beautiful Cinque Terre CSS Dropdown Box with Text Here, we create a dropdown box with some text, that appears when the user mouses over a <div> element. Example <style> .dropdown { position: relative; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 130px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 12px 16px; } .dropdown:hover .dropdown-content { display: block; } </style> <div class="dropdown">Mouse over me! <div class="dropdown-content">Hello World!</div> </div> Try it Yourself » Example Explained The .dropdown class uses position:relative, which is needed when we want the dropdown content to be placed right below the trigger element (the dropdown content will use position:absolute). The .dropdown-content class holds the dropdown content. It is hidden by default, and will be displayed on hover. The min-width property is set to 130px. Feel free to change this! If you want the width of the dropdown content to be as wide as the trigger element, set width to 100% and overflow:auto to enable scroll on small screens. Instead of using a border, we use the box-shadow property to make the dropdown content look like a "card". The :hover selector is used to show the dropdown content when the user mouses over the <div class="dropdown"> element. CSS Dropdown Menu Create a dropdown menu that allows the user to choose an option from a list: Dropdown Menu Link 1 Link 2 Link 3 This example is similar to the previous one, except that we add a button and links inside the dropdown box and style them to fit the dropdown button: Example <style> .dropdown { position: relative; } /* Style the dropdown button */ .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } /* Dropdown content */ .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 200px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); } /* Links inside dropdown content */ .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } /* Change color of dropdown links on hover */ .dropdown-content a:hover { background-color: #f1f1f1 } /* Show the dropdown content on hover */ .dropdown:hover .dropdown-content { display: block; } /* Change background color of dropdown button on hover */ .dropdown:hover .dropbtn { background-color: #3e8e41; } </style> <div class="dropdown"> <button class="dropbtn">Dropdown Menu</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> Try it Yourself » Dropdown Subpages Continue learning about CSS dropdowns: Advanced Dropdowns - right-aligned, images, navbar integration ★ +1 Sign in to track progress
-
CSS Navigation Bars
CSS Navigation Bars A vertical navbar: Home News Contact About A horizontal navbar: Home News Contact About CSS Navigation Bars Having an easy-to-use navigation is important for any website! CSS navigation bars are an important component of web design. Navigation bars helps users to easily navigate between different sections of a website. Navigation bars are typically built with HTML list elements ( <ul> and <li>), and then styled with CSS to get a great look. Navigation bars are typically located at the top or at the side of a webpage. Navigation Bar = List of Links A navigation bar needs standard HTML as a base. A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect sense: Example <ul> <li><a href="default.asp">Home</a></li> <li><a href="news.asp">News</a></li> <li><a href="contact.asp">Contact</a></li> <li><a href="about.asp">About</a></li> </ul> Try it Yourself » Now let's remove the bullets and the margins and padding from the <ul> element: Example ul { list-style-type: none; margin: 0; padding: 0; } Try it Yourself » Example explained: Set list-style-type: none; - Removes the bullet points from list Set margin: 0; - Resets default browser margins Set padding: 0; - Resets default browser paddings Note: The HTML and CSS code in the example above is the base code used for both vertical and horizontal navigation bars, which you will learn more about in the next chapters. ★ +1 Sign in to track progress
-
CSS Opacity
CSS Opacity CSS Image Opacity The opacity property specifies the opacity/transparency of an element. The opacity property can take a value from 0.0 - 1.0: 0.0 - The element will be completely transparent 0.5 - The element will be 50% transparent 1.0 - Default. The element will be fully opaque opacity 0.2 opacity 0.5 opacity 1.0 (default) Example img { opacity: 0.5; } Try it Yourself » Opacity and :hover The opacity property is often used with :hover to change the opacity on mouse-over: Example img { opacity: 0.5; } img:hover { opacity: 1.0; } Try it Yourself » Reversed Hover Effect Here is an example of reversed hover effect: Example img:hover { opacity: 0.5; } Try it Yourself » Transparent Boxes When using the opacity property to add transparency to the background of an element, all child elements inherit the same transparency. This can make the text inside a transparent element hard to read: opacity 1 opacity 0.6 opacity 0.3 opacity 0.1 Example div { opacity: 0.3; } Try it Yourself » Transparency using background-color To NOT apply the transparency to child elements, you can use the background-color property with an RGBA value. RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color. An RGBA color value is specified with: rgba(red, green, blue, alpha). Where the alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque). Tip: You will learn more about RGBA Colors in our CSS Colors Chapter. The following example sets the opacity for the background color and not the text: 100% opacity 60% opacity 30% opacity 10% opacity Example div { background: rgba(4, 170, 109, 0.3) /* Green background with 30% opacity */ } Try it Yourself » Text in Transparent Box This is some text that is placed in the transparent box. Example <html> <head> <style> div.background { background: url(klematis.jpg) repeat; border: 2px solid black; } div.transbox { margin: 30px; background-color: rgba(255, 255, 255, 0.6); border: 1px solid black; } div.transbox p { margin: 5%; font-weight: bold; color: #000000; } </style> </head> <body> <div class="background"> <div class="transbox"> <p>This is some text that is placed in the transparent box.</p> </div> </div> </body> </html> Try it Yourself » Example explained Create a <div> element (class="background") with a background image, and a border. Create another <div> (class="transbox") inside the first <div>. The <div class="transbox"> have a 0.6 transparent background color, and a border. Inside the transparent <div>, we add some text inside a <p> element. CSS Property Property Description opacity Sets the opacity level for an element ★ +1 Sign in to track progress
-
CSS Pseudo-elements
CSS Pseudo-elements CSS Pseudo-Elements A CSS pseudo-element is a keyword that can be added to a selector, to style a specific part of an element. Some common use for pseudo-elements: Style the first letter or first line, of an element Insert content before or after an element Style the markers of list items Style the user-selected portion of an element Style the viewbox behind a dialog box Syntax Pseudo-elements are denoted by a double colon (::) followed by the pseudo-element name: selector::pseudo-element-name { CSS properties } Text Pseudo-elements Text pseudo-elements style specific parts of text content: ::first-line - Style the first line of text ::first-letter - Style the first letter of text Learn more about Text Pseudo-elements » Content Pseudo-elements Content pseudo-elements insert or style generated content: ::before - Insert content before an element ::after - Insert content after an element ::marker - Style list item markers ::selection - Style user-selected text ::backdrop - Style dialog backdrop Learn more about Content Pseudo-elements » CSS Pseudo-elements Reference For a complete list of all CSS Pseudo-elements, visit our CSS Pseudo-elements Reference. ★ +1 Sign in to track progress
-
CSS Pseudo-classes
CSS Pseudo-classes CSS Pseudo-classes A CSS pseudo-class is a keyword that can be added to a selector, to define a style for a special state of an element. Some common use for pseudo-classes: Style an element when a user moves the mouse over it Style visited and unvisited links differently Style an element when it gets focus Style valid/invalid/required/optional form elements Style an element that is the first child of its parent Syntax Pseudo-classes are always denoted by a single colon (:) followed by the pseudo-class name: selector:pseudo-class-name { CSS properties } Mouse Over Me Interactive Pseudo-classes Interactive pseudo-classes apply styles based on user interaction: :hover - When mouse is over an element :focus - When an element has focus :active - When an element is being activated :link - Unvisited links :visited - Visited links Learn more about Interactive Pseudo-classes » Structural Pseudo-classes Structural pseudo-classes select elements based on their position in the document tree: :first-child - First child of a parent :last-child - Last child of a parent :nth-child(n) - The nth child of a parent :lang() - Elements with a specific language Learn more about Structural Pseudo-classes » CSS Pseudo-classes Reference For a complete list of all CSS Pseudo-classes, visit our CSS Pseudo-classes Reference. ★ +1 Sign in to track progress
-
CSS Combinators
CSS Combinators CSS Combinators A combinator is something that defines the relationship between two or more selectors. A CSS selector can contain more than one selector. Between the selectors, we can include a combinator, to create a more specific selection. There are four different combinators in CSS: Descendant combinator (space) Child combinator (>) Next sibling combinator (+) Subsequent-sibling combinator (~) Descendant Combinator (space) The descendant combinator matches all elements that are descendants (children, grandchildren, etc.) of a specified element. The following example selects all <p> elements inside <div> elements: Example div p { background-color: yellow; } Try it Yourself » Child Combinator (>) The child combinator selects all elements that are direct children of a specified element. The following example selects all <p> elements that are direct children of <div>: Example div > p { background-color: yellow; } Try it Yourself » Next Sibling Combinator (+) The next sibling combinator is used to select an element that is directly after a specific element. Sibling elements must have the same parent element. The following example selects the first <p> element that immediately follows a <div>, and share the same parent: Example div + p { background-color: yellow; } Try it Yourself » Subsequent-sibling Combinator (~) The subsequent-sibling combinator selects all elements that are next siblings of a specified element. The following example selects all <p> elements that are next siblings of <div>, and share the same parent: Example div ~ p { background-color: yellow; } Try it Yourself » CSS Combinators Reference For a complete list of all CSS combinators, visit our CSS Combinators Reference. ★ +1 Sign in to track progress
-
CSS Center Align
CSS Center Align Center elements horizontally and vertically CSS Centering Elements With CSS, you can center elements (horizontally, vertically, or both) with several methods, depending on the type of element. Example Center a div element using flexbox: .center { display: flex; justify-content: center; align-items: center; } Try it Yourself » Horizontal Alignment There are several ways to horizontally align elements: margin: auto - Center block elements text-align: center - Center text inside elements float or position - Left/right alignment Learn more about Horizontal Alignment » Vertical Alignment Vertical centering can be achieved using modern layout techniques: Flexbox - Use align-items: center Grid - Use place-items: center Position + Transform - For elements of unknown dimensions Tip: Flexbox is the most modern and recommended method for centering content both horizontally and vertically! Learn more about Vertical Alignment » ★ +1 Sign in to track progress
-
CSS display: inline-block
CSS display: inline-block The CSS display: inline-block The display: inline-block property combines the features of both inline and block elements. An element with display: inline-block will appear on the same line as other inline or inline-block elements. In addition, you can set the width, height, margin-top, and margin-bottom properties for the element (like block elements). The following example shows the different behavior of display: inline, display: inline-block and display: block: Example span.a { display: inline; /* the default for span */ padding: 5px; border: 2px solid red; } span.b { display: inline-block; width: 100px; height: 35px; padding: 5px; border: 2px solid red; } span.c { display: block; width: 100px; height: 35px; padding: 5px; border: 2px solid red; } Try it Yourself » Create a Horizontal Navigation Menu A common use for display: inline-block is to display list items horizontally instead of vertically. The following example creates a horizontal navigation menu: Example Create a horizontal navigation menu: .nav { background-color: lightgray; list-style-type: none; padding: 0; margin: 0; } .nav li { display: inline-block; font-size: 18px; padding: 15px; } Try it Yourself » CSS Property Property Description display Specifies the display behavior (the type of rendering box) of an element ★ +1 Sign in to track progress
-
CSS Float
CSS Float CSS Float The float property specifies how an element should float within its container. It places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The image inside this <div> is floated to the right. If you make the screen smaller, you will see that the text wraps around the image. The CSS float Property The float property is used for positioning and formatting content e.g. let an image float left to the text in a container. This property can have one of the following values: left - The element floats to the left of its container right - The element floats to the right of its container none - Default. The element does not float and is displayed just where it occurs in the text inherit - The element inherits the float value of its parent Tip: The float property is often used to wrap text around images! CSS float: right Example The float: right value indicates that an element should float to the right within its container. The following example specifies that the image should float to the right: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac... Example img { float: right; } Try it Yourself » CSS float: left Example The float: left value indicates that an element should float to the left within its container. The following example specifies that the image should float to the left: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac... Example img { float: left; } Try it Yourself » CSS float: none Example The float: none value is the default value for float, and the element is displayed just where it occurs in its container. In the following example the image will be displayed just where it occurs in the container: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac... Example img { float: none; } Try it Yourself » CSS Float Next To Each Other HTML <div> elements are block elements, and will start on a new line and take up the full width available. However, if we use float: left we can make the <div> elements to float next to each other: Example div { float: left; padding: 15px; } .div1 { background: red; } .div2 { background: yellow; } .div3 { background: green; } Try it Yourself » CSS Float Property Property Description float Specifies whether an element should float to the left, right, or not at all ★ +1 Sign in to track progress