所有动态
- 一小时前
-
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
-
CSS Outline
CSS Outline An outline is a line drawn around an element, outside the element's border. This element has a black border and a green outline with a width of 10px. Try it Yourself » CSS Outline An outline is a line that is drawn around elements, OUTSIDE the borders, to make the element "stand out". Note: Outline differs from borders! The outline is drawn outside the element's border, and may overlap other content. Also, the outline is NOT a part of the element's dimensions; the element's total width and height is not affected by the width of the outline. CSS has the following outline properties: outline-style - Specifies the style of the outline outline-color - Specifies the color of the outline outline-width - Specifies the width of the outline outline-offset - Adds space between the outline and the edge/border of an element outline - A shorthand property CSS The outline-style Property The outline-style property specifies the style of the outline, and can have one of the following values: dotted - Defines a dotted outline dashed - Defines a dashed outline solid - Defines a solid outline double - Defines a double outline groove - Defines a 3D grooved outline ridge - Defines a 3D ridged outline inset - Defines a 3D inset outline outset - Defines a 3D outset outline none - Defines no outline hidden - Defines a hidden outline The following example shows the different outline-style values: Example Demonstration of the different outline styles: p.dotted {outline-style: dotted;} p.dashed {outline-style: dashed;} p.solid {outline-style: solid;} p.double {outline-style: double;} p.groove {outline-style: groove;} p.ridge {outline-style: ridge;} p.inset {outline-style: inset;} p.outset {outline-style: outset;} Result: A dotted outline. A dashed outline. A solid outline. A double outline. A groove outline. The effect depends on the outline-color value. A ridge outline. The effect depends on the outline-color value. An inset outline. The effect depends on the outline-color value. An outset outline. The effect depends on the outline-color value. Try it Yourself » Note: None of the other outline properties (which you will learn more about in the next chapters) will have ANY effect unless the outline-style property is set! ★ +1 Sign in to track progress
-
CSS Box Model
CSS Box Model The CSS Box Model In CSS, the term "box model" is used when talking about web design and layout. The CSS box model is essentially a box that wraps around every HTML element. Every box consists of four parts: content, padding, borders and margins. The image below illustrates the CSS box model: Explanation of the different parts (from innermost part to outermost part): Content - The content of the box, where text and images appear Padding - Clears an area around the content. The padding is transparent Border - A border that goes around the padding and content Margin - Clears an area outside the border. The margin is transparent The box model allows us to add a border around elements, and to define space between elements. Example Demonstration of the box model: div { width: 300px; border: 15px solid green; padding: 50px; margin: 20px; } Try it Yourself » Width and Height of an Element In order to set the width and height of an element correctly in all browsers, you need to know how the box model works. Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the total width and height of an element, you must also include the padding and borders. Example This <div> element will have a total width of 350px and a total height of 80px: div { width: 320px; height: 50px; padding: 10px; border: 5px solid gray; margin: 0; } Try it Yourself » Here is the calculation: 320px (width of content area) + 20px (left padding + right padding) + 10px (left border + right border) = 350px (total width) 50px (height of content area) + 20px (top padding + bottom padding) + 10px (top border + bottom border) = 80px (total height) The total width of an element should be calculated like this: Total element width = width + left padding + right padding + left border + right border The total height of an element should be calculated like this: Total element height = height + top padding + bottom padding + top border + bottom border Note: The margin property also affects the total space that the box will take up on the page, but the margin is not included in the actual size of the box. The box's total width and height stops at the border. ★ +1 Sign in to track progress
-
CSS Height and Width
CSS Height and Width CSS Height and Width The CSS height and width properties are used to set the height and width of an element. This element has a height of 70 pixels and a width of 100%. Try it Yourself » CSS Set height and width The height and width properties are used to set the height and width of an element. The height and width do not include padding, borders, or margins. It sets the height and width of the area inside the padding, border, and margin of the element. CSS height and width Values The height and width properties can have the following values: auto - This is default. The browser calculates the height and width length - Defines the height or width in px, cm, em, etc. % - Defines the height or width in percent of the containing block initial - Sets the height or width to its default value inherit - The height or width will be inherited from its parent value CSS height and width Examples This element has a height of 200 pixels and a width of 50% Example Set the height and width of a <div> element: div { height: 200px; width: 50%; background-color: powderblue; } Try it Yourself » This element has a height of 100 pixels and a width of 500 pixels. Example Set the height and width of another <div> element: div { height: 100px; width: 500px; background-color: powderblue; } Try it Yourself » Note: Remember that the height and width properties do not include padding, borders, or margins! They set the height/width of the area inside the padding, border, and margin of the element! Try it Yourself - Examples Set the height and width of elements This example demonstrates how to set the height and width of different elements. Set the height and width of an image using percent This example demonstrates how to set the height and width of an image using a percent value. ★ +1 Sign in to track progress
-
CSS Padding
CSS Padding This element has a padding of 70px. Try it Yourself » CSS Padding The CSS padding properties are used to generate space around an element's content, inside of any defined borders. With CSS, you have full control over the padding. There are properties for setting the padding for each side of an element (top, right, bottom, and left), and a shorthand property for setting all the padding properties in one declaration. Padding - Individual Sides CSS has properties for specifying the padding for each side of an element: padding-top - sets the top padding of an element padding-right - sets the right padding of an element padding-bottom - sets the bottom padding of an element padding-left - sets the left padding of an element All the padding properties can have the following values: length - specifies a padding in px, pt, cm, etc. % - specifies a padding in % of the width of the containing element inherit - specifies that the padding should be inherited from the parent element Note: Negative values are not allowed. Example Set different padding for all four sides of a <div> element: div { padding-top: 50px; padding-right: 30px; padding-bottom: 50px; padding-left: 80px; } Try it Yourself » Padding - Shorthand Property To shorten the code, it is possible to specify all the padding properties in one declaration. The padding property is a shorthand property for the following individual padding properties: padding-top padding-right padding-bottom padding-left Here is how it works: If the padding property has four values: padding: 25px 50px 75px 100px; top padding is 25px right padding is 50px bottom padding is 75px left padding is 100px Example Use the padding shorthand property with four values: div { padding: 25px 50px 75px 100px; } Try it Yourself » If the padding property has three values: padding: 25px 50px 75px; top padding is 25px right and left paddings are 50px bottom padding is 75px Example Use the padding shorthand property with three values: div { padding: 25px 50px 75px; } Try it Yourself » If the padding property has two values: padding: 25px 50px;top and bottom paddings are 25px right and left paddings are 50px Example Use the padding shorthand property with two values: div { padding: 25px 50px; } Try it Yourself » If the padding property has one value: padding: 25px;all four paddings are 25px Example Use the padding shorthand property with one value: div { padding: 25px; } Try it Yourself » More Examples Set the left-padding property This example demonstrates how to set the left padding of a <p> element. Set the right-padding property This example demonstrates how to set the right padding of a <p> element. Set the top-padding property This example demonstrates how to set the top padding of a <p> element. Set the bottom-padding property This example demonstrates how to set the bottom padding of a <p> element. ★ +1 Sign in to track progress
-
CSS Margins
CSS Margins This element has a margin of 70px. Try it Yourself » CSS Margins The CSS margin properties are used to create space around elements, outside of any defined borders. Margins define the distance between an element's border and the surrounding elements. With CSS, you have full control over the margins. CSS has properties for setting the margin for each individual side of an element (top, right, bottom, and left), and a shorthand property for setting all the margin properties in one declaration. Margin - Individual Sides CSS has properties for specifying the margin for each side of an element: margin-top - sets the top margin of an element margin-right - sets the right margin of an element margin-bottom - sets the bottom margin of an element margin-left - sets the left margin of an element All the margin properties can have the following values: auto - the browser calculates the margin length - specifies a margin in px, pt, cm, etc. % - specifies a margin in % of the width of the containing element inherit - specifies that the margin should be inherited from the parent element Tip: Negative values are also allowed. Example Set different margins for all four sides of a <p> element: p { margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 80px; } Try it Yourself » Margin - Shorthand Property To shorten the code, it is possible to specify all the margin properties in one declaration. The margin property is a shorthand property for the following individual margin properties: margin-top margin-right margin-bottom margin-left Here is how it works: If the margin property has four values: margin: 25px 50px 75px 100px; top margin is 25px right margin is 50px bottom margin is 75px left margin is 100px Example Use the margin shorthand property with four values: p { margin: 25px 50px 75px 100px; } Try it Yourself » If the margin property has three values: margin: 25px 50px 75px; top margin is 25px right and left margins are 50px bottom margin is 75px Example Use the margin shorthand property with three values: p { margin: 25px 50px 75px; } Try it Yourself » If the margin property has two values: margin: 25px 50px;top and bottom margins are 25px right and left margins are 50px Example Use the margin shorthand property with two values: p { margin: 25px 50px; } Try it Yourself » If the margin property has one value: margin: 25px;all four margins are 25px Example Use the margin shorthand property with one value: p { margin: 25px; } Try it Yourself » The auto Value You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins. Example Use margin: auto: div { width: 300px; margin: auto; border: 1px solid red; } Try it Yourself » The inherit Value You can set the margin property to inherit to let the margin be inherited from the parent element. This example lets the left margin of the <p class="ex1"> element be inherited from the parent element (<div>): Example Use of the inherit value: div { border: 1px solid red; margin-left: 100px; } p.ex1 { margin-left: inherit; } Try it Yourself » All CSS Margin Properties Property Description margin A shorthand property for setting all the margin properties in one declaration margin-bottom Sets the bottom margin of an element margin-left Sets the left margin of an element margin-right Sets the right margin of an element margin-top Sets the top margin of an element ★ +1 Sign in to track progress
-
CSS Borders
CSS Borders CSS Borders The CSS border properties allow you to specify the style, width, and color of an element's border. I have borders on all sides. I have a red, bottom border. I have rounded borders. I have a blue, left border. CSS Border Style The border-style property specifies what kind of border to display. The following values are allowed: dotted - Defines a dotted border dashed - Defines a dashed border solid - Defines a solid border double - Defines a double border groove - Defines a 3D grooved border. The effect depends on the border-color value ridge - Defines a 3D ridged border. The effect depends on the border-color value inset - Defines a 3D inset border. The effect depends on the border-color value outset - Defines a 3D outset border. The effect depends on the border-color value none - Defines no border hidden - Defines a hidden border The border-style property can have from one to four values (for the top border, right border, bottom border, and the left border). Example Demonstration of the different border styles: p.dotted {border-style: dotted;} p.dashed {border-style: dashed;} p.solid {border-style: solid;} p.double {border-style: double;} p.groove {border-style: groove;} p.ridge {border-style: ridge;} p.inset {border-style: inset;} p.outset {border-style: outset;} p.none {border-style: none;} p.hidden {border-style: hidden;} p.mix {border-style: dotted dashed solid double;} Result: A dotted border. A dashed border. A solid border. A double border. A groove border. The effect depends on the border-color value. A ridge border. The effect depends on the border-color value. An inset border. The effect depends on the border-color value. An outset border. The effect depends on the border-color value. No border. A hidden border. A mixed border. Try it Yourself » Note: None of the OTHER CSS border properties (which you will learn more about in the next chapters) will have ANY effect unless the border-style property is set! ★ +1 Sign in to track progress
-
CSS Backgrounds
CSS Backgrounds CSS Backgrounds The CSS background properties are used to add background effects for elements. In these chapters, you will learn about the following CSS background properties: background-color background-image background-repeat background-attachment background-position background (shorthand property) CSS background-color The background-color property specifies the background color of an element. Example The background color of a page is set like this: body { background-color: lightblue; } Try it Yourself » With CSS, a color is most often specified by: a valid 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. Other Elements You can set the background color for any HTML elements: Example Here, the <h1>, <p>, and <div> elements will have different background colors: h1 { background-color: green; } div { background-color: lightblue; } p { background-color: yellow; } Try it Yourself » Opacity / Transparency The opacity property specifies the opacity/transparency of an element. It can take a value from 0.0 - 1.0. The lower value, the more transparent: opacity 1 opacity 0.6 opacity 0.3 opacity 0.1 Example div { background-color: green; opacity: 0.3; } Try it Yourself » Note: When using the opacity property to add transparency to the background of an element, all of its child elements inherit the same transparency. This can make the text inside a fully transparent element hard to read. Transparency using RGBA If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. The following example sets the opacity for the background color and not the text: 100% opacity 60% opacity 30% opacity 10% opacity You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - 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). Tip: You will learn more about RGBA Colors in our CSS Colors Chapter. Example div { background: rgba(0, 128, 0, 0.3) /* Green background with 30% opacity */ } Try it Yourself » The CSS Background Color Property Property Description background-color Sets the background color of an element Video: CSS Background Color ★ +1 Sign in to track progress
-
CSS Colors
CSS Colors CSS Colors In CSS, colors are specified by using a predefined color name, or with a RGB, HEX, HSL, RGBA, HSLA value. CSS Color Names In CSS, a color can be specified by using a predefined color name: Tomato Orange DodgerBlue MediumSeaGreen Gray SlateBlue Violet LightGray Try it Yourself » CSS/HTML support 140 standard color names. CSS Background Color You can set the background color for HTML elements: Hello World 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 <h1 style="background-color:DodgerBlue;">Hello World</h1> <p style="background-color:Tomato;">Lorem ipsum...</p> Try it Yourself » CSS Text Color You can set the color of text: Hello World 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 <h1 style="color:Tomato;">Hello World</h1> <p style="color:DodgerBlue;">Lorem ipsum...</p> <p style="color:MediumSeaGreen;">Ut wisi enim...</p> Try it Yourself » CSS Border Color You can set the color of borders: Hello World Hello World Hello World Example <h1 style="border:2px solid Tomato;">Hello World</h1> <h1 style="border:2px solid DodgerBlue;">Hello World</h1> <h1 style="border:2px solid Violet;">Hello World</h1> Try it Yourself » CSS Color Values In CSS, colors can also be specified using RGB values, HEX values, HSL values, RGBA values, and HSLA values: Same as color name "Tomato": rgb(255, 99, 71) #ff6347 hsl(9, 100%, 64%) Same as color name "Tomato", but 50% transparent: rgba(255, 99, 71, 0.5) hsla(9, 100%, 64%, 0.5) Example <h1 style="background-color:rgb(255, 99, 71);">...</h1> <h1 style="background-color:#ff6347;">...</h1> <h1 style="background-color:hsl(9, 100%, 64%);">...</h1> <h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1> <h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1> Try it Yourself » Learn more about Color Values You will learn more about RGB, HEX and HSL in the next chapters. Video: CSS Colors Introduction ★ +1 Sign in to track progress
-
CSS Errors
CSS Errors CSS Errors Errors in CSS can lead to unexpected behavior or styles not being applied correctly. This page shows common CSS mistakes and how to avoid them. Missing Semicolons Forgetting a semicolon at the end of a property declaration can break the style rule. Example .bad { color: red background-color: yellow; } Try it Yourself » Invalid Property Names Using a property name that does not exist will simply be ignored by the browser. Example .bad { colr: blue; font-size: 16px; } Try it Yourself » Invalid Values Correct properties but invalid values will also be ignored. Example .bad { width: -100px; color: green; } Try it Yourself » Unclosed Braces If you forget to close a brace }, the entire rule may be ignored. Example .bad { padding: 20px; margin: 10px; Try it Yourself » Extra Colons or Braces Typos like extra colons or misplaced braces can cause rules to break. Example .bad { color:: blue; } Try it Yourself » Tips to Avoid CSS Errors Use a code editor with syntax highlighting. Validate your CSS with a CSS linter or validator. Write CSS in small sections and test frequently. ★ +1 Sign in to track progress
-
CSS Comments
CSS Comments CSS Comments Comments are used to explain the CSS code, and may help when you edit the source code at a later date. Comments are also used to temporarily disable sections of CSS code within a stylesheet. Comments are ignored by browsers! A CSS comment is placed inside the HTML <style> element, and starts with /* and ends with */: Example /* This is a single-line comment */ p { color: red; } Try it Yourself » You can add comments wherever you want in the code: Example p { color: red; /* Set text color to red */ } Try it Yourself » Even in the middle of a code line: Example p { color: /*red*/blue; } Try it Yourself » Comments can also span multiple lines: Example /* This is a multi-line comment */ p { color: red; } Try it Yourself » HTML and CSS Comments From the HTML tutorial, you learned that you can add comments to your HTML source by using the <!--...--> syntax. In the following example, we use a combination of HTML and CSS comments: Example <!DOCTYPE html> <html> <head> <style> p { color: red; /* Set text color to red */ } </style> </head> <body> <h2>My Heading</h2> <!-- These paragraphs will be red --> <p>Hello World!</p> <p>This paragraph is styled with CSS.</p> <p>HTML and CSS comments are not shown in the output.</p> </body> </html> Try it Yourself » Video: CSS Comments ★ +1 Sign in to track progress