所有动态
- 一小时前
-
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
-
CSS The z-index Property
CSS The z-index Property The CSS z-index Property The z-index property specifies the stack order of positioned elements. The stack order defines which element should be placed in front or behind other elements. When elements are positioned, they can overlap other elements. An element can have a positive or negative stack order (z-index): This is a heading Because the image has a z-index of -1, it will be placed behind the text. Example img { position: absolute; left: 0px; top: 0px; z-index: -1; } Try it Yourself » Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display: flex elements). Another z-index Example A postioned element with a greater stack order is always above an element with a lower stack order. Example <html> <head> <style> .container { position: relative; } .black-box { position: relative; z-index: 1; border: 2px solid black; height: 100px; margin: 30px; } .gray-box { position: absolute; z-index: 3; background: lightgray; height: 60px; width: 70%; left: 50px; top: 50px; } .green-box { position: absolute; z-index: 2; background: lightgreen; width: 35%; left: 270px; top: -15px; height: 100px; } </style> </head> <body> <div class="container"> <div class="black-box">Black box</div> <div class="gray-box">Gray box</div> <div class="green-box">Green box</div> </div> </body> </html> Try it Yourself » Without z-index If several positioned elements overlap each other without a z-index specified, the elements render in the order they are defined in the HTML source code. Example Same example as above, but here with no z-index specified: <html> <head> <style> .container { position: relative; } .black-box { position: relative; border: 2px solid black; height: 100px; margin: 30px; } .gray-box { position: absolute; background: lightgray; height: 60px; width: 70%; left: 50px; top: 50px; } .green-box { position: absolute; background: lightgreen; width: 35%; left: 270px; top: -15px; height: 100px; } </style> </head> <body> <div class="container"> <div class="black-box">Black box</div> <div class="gray-box">Gray box</div> <div class="green-box">Green box</div> </div> </body> </html> Try it Yourself » CSS Property Property Description z-index Sets the stack order of an element ★ +1 Sign in to track progress
-
CSS Position Offsets
CSS Position Offsets Positioning with top, right, bottom, and left The top, right, bottom, and left properties are used to position elements. These properties only work on positioned elements (elements with position set to relative, absolute, fixed, or sticky). Positioning Text On an Image How to position text on an image: Example Bottom Left Top Left Top Right Bottom Right Centered Try it Yourself: Top Left » Top Right » Bottom Left » Bottom Right » Centered » All CSS Positioning Properties Property Description bottom Sets the bottom margin edge for a positioned box clip Clips an absolutely positioned element left Sets the left margin edge for a positioned box position Specifies the type of positioning for an element right Sets the right margin edge for a positioned box top Sets the top margin edge for a positioned box ★ +1 Sign in to track progress
-
CSS The position Property
CSS The position Property CSS Positioning CSS positioning is about controlling the placement of elements within a web page. With CSS positioning, you can override the normal document flow. The CSS position Property The position property specifies the positioning type for an element. This property can have one of the following values: static - This is default relative fixed absolute sticky Elements are then positioned to their final location with the top, bottom, left, and right properties. CSS position: static All HTML elements are positioned static by default. Static positioned elements are not affected by the top, bottom, left, and right properties. An element with position: static; is always positioned according to the normal flow of the page: This <div> element has position: static; Here is the CSS that is used: Example div.static { position: static; border: 3px solid #73AD21; } Try it Yourself » CSS position: relative An element with position: relative; is positioned relative to its normal position in the document flow. Setting the top, right, bottom, and left properties will cause the element to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element. This <div> has position: relative, and is skewed 30 px to the right of its normal position Here is the CSS that is used: Example div.relative { position: relative; left: 30px; border: 3px solid #73AD21; } Try it Yourself » ★ +1 Sign in to track progress
-
CSS The max-width Property
CSS The max-width Property The CSS max-width Property The max-width property defines the maximum width of an element. This property prevents the element's width from being larger than the specified value (it can be smaller, but not larger). This property is useful for creating responsive layouts and to ensure content readability across various screen sizes. Problem with width: Here we have a horizontally centered <div> element with a specific width (600px): This <div> element has a width of 600px, and margin set to auto. This <div> element has a width of 600px, and margin set to auto. What happens to the <div> above if the browser window is smaller than the width of the element? Some of the content will not show, and the browser might add a horizontal scrollbar to the page. Using max-width instead: Now, we use the max-width property instead. This will improve the browser's handling of small windows: This <div> element has a max-width of 600px, and margin set to auto. This <div> element has a max-width of 600px, and margin set to auto. Tip: Resize the browser window to less than 600px wide, to see the difference between the two <div>s! Here is the CSS code for the two <div>s above: Example div.ex1 { width: 500px; margin: auto; border: 3px solid #73AD21; } div.ex2 { max-width: 500px; margin: auto; border: 3px solid #73AD21; } Try it Yourself » CSS Properties Property Description max-width Defines the maximum width of an element width Sets the width of an element ★ +1 Sign in to track progress
-
CSS Tables
CSS Tables HTML tables can be greatly improved with CSS: Company Contact Country Alfreds Futterkiste Maria Anders Germany Berglunds snabbköp Christina Berglund Sweden Centro comercial Moctezuma Francisco Chang Mexico Ernst Handel Roland Mendel Austria Island Trading Helen Bennett UK Königlich Essen Philip Cramer Germany Laughing Bacchus Winecellars Yoshi Tannamuri Canada Magazzini Alimentari Riuniti Giovanni Rovelli Italy Try it Yourself » CSS Table Borders The CSS border property is used to specify the width, style, and color of table borders. The border property is a shorthand property for: border-width - sets the width of the border border-style - sets the style of the border (required) border-color - sets the color of the border The example below specifies a 1px solid border for <table>, <th>, and <td> elements: Firstname Lastname Peter Griffin Lois Griffin Example table, th, td { border: 1px solid; } Try it Yourself » CSS Table Border Color The example below specifies a 1px solid green border for <table>, <th>, and <td> elements: Firstname Lastname Peter Griffin Lois Griffin Example table, th, td { border: 1px solid green; } Try it Yourself » Why Double Borders? Notice that the tables in the examples above have double borders. This is because both the <table>, <th>, and <td> elements have separate borders. To remove double borders, take a look at the example below. CSS Collapse Table Borders The CSS border-collapse property sets whether table borders should collapse into a single border or be separated as in standard HTML. This property can have one of the following values: separate - Default value. Borders are separated; each cell will display its own borders collapse - Borders are collapsed into a single border when possible The following table has collapsed borders: Firstname Lastname Peter Griffin Lois Griffin Example Using the border-collapse property: table { border-collapse: collapse; } Try it Yourself » CSS Table Padding To control the space between the border and the content in a table, use the padding property on <td> and <th> elements: First Name Last Name Savings Peter Griffin $100 Lois Griffin $150 Joe Swanson $300 Example th, td { padding: 10px; } Try it Yourself » CSS Border Spacing The CSS border-spacing property sets the distance between the borders of adjacent cells. Note: This property works only when border-collapse is set to "separate". The following table has a border-spacing of 15px: Firstname Lastname Peter Griffin Lois Griffin Example Using the border-spacing property: table { border-collapse: separate; border-spacing: 15px; } Try it Yourself » CSS Outside Table Borders If you just want a border around the table (not inside), you specify the border property only for the <table> element: Firstname Lastname Peter Griffin Lois Griffin Example table { border: 1px solid; } Try it Yourself » ★ +1 Sign in to track progress
-
CSS Lists
CSS Lists An unordered list: Coffee Tea Coca Cola An ordered list: Coffee Tea Coca Cola CSS Styling Lists In HTML, there are two main types of lists: <ul> - unordered lists (list items are marked with bullets) <ol> - ordered lists (list items are marked with numbers or letters) CSS has the following properties for styling HTML lists: list-style-type - Specifies the type of list-item marker list-style-image - Specifies an image as the list-item marker list-style-position - Specifies the position of the list-item markers list-style - A shorthand property for the properties above CSS Style List-item Markers The CSS list-style-type property specifies the type of list-item marker in a list. The following example shows some of the available list-item markers: Example ul.a {list-style-type: circle;} ul.b {list-style-type: disc;} ul.c {list-style-type: square;} ol.d {list-style-type: upper-roman;} ol.e {list-style-type: lower-roman;} ol.f {list-style-type: lower-alpha;} ol.g {list-style-type: decimal;} Try it Yourself » Note: Some of the values are for unordered lists, and some for ordered lists. CSS Replace List-item Marker with an Image The CSS list-style-image property is used to replace the list-item marker with an image. Note: Always specify a list-style-type property in addition. This property is used if the image for some reason is unavailable. Example Replace the list-item markers with an image: ul { list-style-image: url('sqpurple.gif'); list-style-type: square; } Try it Yourself » CSS Position the List-item Markers The CSS list-style-position property specifies the position of the list-item markers (bullet points). list-style-position: outside; means that the bullet points will be outside the list item. The start of each line of a list item will be aligned vertically. This is default: Coffee Tea Coca-cola list-style-position: inside; means that the bullet points will be inside the list item. As it is part of the list item, it will be part of the text and push the text at the start: Coffee Tea Coca-cola Example Position the list-item markers: ul.a { list-style-position: outside; } ul.b { list-style-position: inside; } Try it Yourself » CSS Remove List-Item Markers The list-style-type:none; property is used to remove the list-item markers. Note: A list has a default margin and padding. To remove this, add margin:0 and padding:0 to the <ul> or <ol> element: Example Remove the list-item markers: ul { list-style-type: none; margin: 0; padding: 0; } Try it Yourself » CSS list-style Shorthand Property The list-style property is a shorthand property. It is used to set all the list properties in one declaration. When using the shorthand property, the order of the property values are: list-style-type list-style-position list-style-image If one of the property values above is missing, the default value for the missing property will be inserted. Example Use the list-style shorthand property: ul { list-style: square inside url("sqpurple.gif"); } Try it Yourself » CSS Styling List With Colors We can also style lists with colors, margins and padding, to make them look a little more interesting. Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to the <li> tag will affect the individual list items: Example Styling lists with colors, margins and padding: ol { background: salmon; padding: 20px; } ol li { background: mistyrose; color: darkred; padding: 10px; margin-left: 20px; } ul { background: powderblue; padding: 20px; } ul li { background: mistyrose; color: darkblue; margin: 5px; } Result: Coffee Tea Coca Cola Coffee Tea Coca Cola Try it Yourself » More Examples Customized list with a red left border This example demonstrates how to create a list with a red left border. Full-width bordered list This example demonstrates how to create a bordered list without bullets. All the different list-item markers for lists This example demonstrates all the different list-item markers in CSS. All CSS List Properties Property Description list-style Sets all the properties for a list in one declaration list-style-image Specifies an image as the list-item marker list-style-position Specifies the position of the list-item markers (bullet points) list-style-type Specifies the type of list-item marker ★ +1 Sign in to track progress
-
CSS Links
CSS Links Text Link Text Link CSS Styling Links HTML links can be styled with many CSS properties, like color, text-decoration, background-color, font-size, font-weight, font-family, etc.). Example Style a link with a color, background-color, and a bold font-weight: a { color: hotpink; background-color: yellow; font-weight: bold; } Try it Yourself » Styling Links Depending on State In addition, links can be styled differently depending on what state they are in. The four link states are: :link - a normal, unvisited link :visited - a link the user has visited :hover - a link when the user mouses over it :active - a link the moment it is clicked When setting the style for link states, there are some order rules: :hover must come after :link and :visited :active must come after :hover Example Style links according to link state: /* unvisited link */ a:link { color: red; } /* visited link */ a:visited { color: green; } /* mouse over link */ a:hover { color: hotpink; } /* selected link */ a:active { color: blue; } Try it Yourself » CSS Links - Text Decoration The text-decoration property is mostly used to remove underlines from links: Example a:link { text-decoration: none; } a:visited { text-decoration: none; } a:hover { text-decoration: underline; } a:active { text-decoration: underline; } Try it Yourself » CSS Links - Background Color The background-color property can be used to specify a background color for links: Example a:link { background-color: yellow; } a:visited { background-color: cyan; } a:hover { background-color: lightgreen; } a:active { background-color: hotpink; } Try it Yourself » More Examples Example This example demonstrates how to add other styles to HTML links: a.one:link {color:red;} a.one:visited {color:blue;} a.one:hover {color:orange;} a.two:link {color:red;} a.two:visited {color:blue;} a.two:hover {font-size:150%;} a.three:link {color:red;} a.three:visited {color:blue;} a.three:hover {background:lightgreen;} a.four:link {color:red;} a.four:visited {color:blue;} a.four:hover {font-family:monospace;} a.five:link {color:red;text-decoration:none;} a.five:visited {color:blue;text-decoration:none;} a.five:hover {text-decoration:underline;} Try it Yourself » Example This example demonstrates the different types of cursors (can be useful for links): <span style="cursor: auto">auto</span><br> <span style="cursor: crosshair">crosshair</span><br> <span style="cursor: default">default</span><br> <span style="cursor: e-resize">e-resize</span><br> <span style="cursor: help">help</span><br> <span style="cursor: move">move</span><br> <span style="cursor: n-resize">n-resize</span><br> <span style="cursor: ne-resize">ne-resize</span><br> <span style="cursor: nw-resize">nw-resize</span><br> <span style="cursor: pointer">pointer</span><br> <span style="cursor: progress">progress</span><br> <span style="cursor: s-resize">s-resize</span><br> <span style="cursor: se-resize">se-resize</span><br> <span style="cursor: sw-resize">sw-resize</span><br> <span style="cursor: text">text</span><br> <span style="cursor: w-resize">w-resize</span><br> <span style="cursor: wait">wait</span> Try it Yourself » ★ +1 Sign in to track progress
-
CSS Icons - Font Awesome
CSS Icons - Font Awesome Icons can easily be added to your HTML page, by using an icon library. How To Add Icons The simplest way to add an icon to your HTML page, is with an icon library, such as Font Awesome. Add the name of the specified icon class to any inline HTML element (like <i> or <span>). All the icons in the icon libraries below, are scalable vectors that can be customized with CSS (size, color, shadow, etc.) Font Awesome Icons To use the Font Awesome icons, go to fontawesome.com, sign in, and get a code to add in the <head> section of your HTML page: <script src="https://kit.fontawesome.com/yourcode.js" crossorigin="anonymous"></script> Read more about how to get started with Font Awesome in our Font Awesome 5 tutorial. Note: No downloading or installation is required! Example <!DOCTYPE html> <html> <head> <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script> </head> <body> <i class="fas fa-cloud"></i> <i class="fas fa-heart"></i> <i class="fas fa-car"></i> <i class="fas fa-file"></i> <i class="fas fa-bars"></i> </body> </html> Result: Try It Yourself » For a complete reference of all Font Awesome icons, visit our Icon Reference. ★ +1 Sign in to track progress
-
CSS Fonts
CSS Fonts Font Selection is Important Choosing the right font has a huge impact on how the readers experience a website. The right font can create a strong identity for your brand. Choosing a font that is easy to read is important. It is also important to choose a good color and size for your font. The CSS font-family Property The CSS font-family property specifies the font for an element. Tip: The font-family property should hold several font names as a "fallback" system. If the browser does not support the first font, it tries the next font. The font names should be separated with a comma. Always start with the font you want, and always end with a generic family, to let the browser pick a similar font in the generic family, if no other fonts are available. Note: If the font name is more than one word, it must be in quotation marks, like: "Times New Roman". Tip: Read more about fallback fonts in CSS Web Safe Fonts. Example Specify some different fonts for three paragraphs: .p1 { font-family: "Times New Roman", Times, serif; } .p2 { font-family: Arial, Helvetica, sans-serif; } .p3 { font-family: "Lucida Console", "Courier New", monospace; } Try it Yourself » CSS Generic Font Families In CSS, there are five generic font families: Serif fonts - have a small stroke at the edges of each letter. They create a sense of formality and elegance. Sans-serif fonts - have clean lines (no small strokes attached). They create a modern and minimalistic look. Monospace fonts - here all the letters have the same fixed width. They create a mechanical look. Cursive fonts - imitate human handwriting. Fantasy fonts - are decorative/playful fonts. All the different font names belong to one of the generic font families. Difference Between Serif and Sans-serif Fonts Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts. Some Font Examples Generic Font Family Examples of Font Names Serif Times New Roman Georgia Garamond Sans-serif Arial Verdana Helvetica Monospace Courier New Lucida Console Monaco Cursive Brush Script MT Lucida Handwriting Fantasy Copperplate Papyrus ★ +1 Sign in to track progress
-
CSS Text Color
CSS Text Color CSS has a lot of properties for styling and formatting text. text formatting This text is styled with some of the text formatting properties. The heading uses the text-align, text-transform, and color properties. The paragraph is indented, aligned, and the space between characters is specified. The underline is removed from this colored "Try it Yourself" link. Try it Yourself » CSS Text Color The color property is used to set the color of the text. The color is specified by: a color name - like "red" a HEX value - like "#ff0000" an RGB value - like "rgb(255,0,0)" Look at CSS Color Values for a complete list of possible color values. The default text color for a page is defined in the body selector. Example body { color: blue; } h1 { color: green; } h2 { color: red; } Try it Yourself » Text Color and Background Color In this example, we define both the background-color property and the color property: Example body { background-color: lightgrey; color: blue; } h1 { background-color: black; color: white; } div { background-color: blue; color: white; } Try it Yourself » Important: High contrast is very important for people with vision problems. So, always ensure that the contrast between the text color and the background color (or background image) is good! The CSS Text Color Property Property Description color Specifies the color of text ★ +1 Sign in to track progress