CSS - Riptutorial

Transcription

CSS#css

Table of ContentsAbout1Chapter 1: Getting started with CSS2Remarks2Versions2Examples2External StylesheetExample22Internal Styles4Inline Styles4CSS @import rule (one of CSS at-rule)4How to use @import5Changing CSS with JavaScript5Pure JavaScript5jQuery5See also6Styling Lists with CSSChapter 2: 2D Transforms68Syntax8Parameters8Remarks92D Coordiante system9Browser support and prefixes10Example of prefixed ew11Multiple transforms12Transform Origin13

Chapter 3: 3D Transforms15Remarks15Coordinate system15Examples153D cube16backface-visibility17Compass pointer or needle shape using 3D transforms18CSS18HTML183D text effect with shadowChapter 4: ions with the transition property22Example22Cross-Browser Compatibility23Increasing Animation Performance Using the will-change Attribute24Animations with keyframes24Basic Example24Cross-browser compatibility26Syntax ExamplesChapter 5: ples27Background Color27Color names28Hex color codes28RGB / RGBa28

HSL / HSLa29Interaction with background-image29Background Image30Background epeating gradients32Background Shorthand33Syntax33Examples33Background PositionLonghand Background Position PropertiesBackground AttachmentExamples34353535background-attachment: scroll35background-attachment: fixed36background-attachment: local36Background Repeat36Background Color with Opacity37Multiple Background Image37The background-origin property38Background Clip40Background Size41General overview41Keeping the aspect ratio43Eggsplanation for contain and cover43contain44cover44Demonstration with actual code45background-blend-mode Property46Chapter 6: Block Formatting Contexts47

Remarks47Examples47Using the overflow property with a value different to visibleChapter 7: 51border-style52border (shorthands)53border-image53border-[left right top bottom]54border-collapse54Multiple Borders54Creating a multi-colored border using border-image55CSS55HTML56Chapter 8: 8drop shadow58inner drop shadow59bottom-only drop shadow using a pseudo-element59multiple shadows60Chapter 9: Browser Support & ns62Transform63

Chapter 10: Cascading and Specificity64Remarks64Examples64Cascading64CSS Loading order64How are conflicts resolved?64Example 1 - Specificity rules64Example 2 - Cascade rules with identical selectors65Example 3 - Cascade rules after Specificity rules65A final note65The !important declaration66Calculating Selector Specificity66Example 1: Specificity of various selector sequences67Example 2: How specificity is used by the browser67Example 3: How to manipulate specificity68!important and inline style declarations69A final note69More complex specificity example69Chapter 11: CenteringExamples7171Using CSS transform71CROSS BROWSER COMPATIBILITY71MORE INFORMATION72Using Flexbox72Using position: absolute73Ghost element technique (Micha Czernow's hack)74Using text-align74Centering in relation to another item75Vertical align anything with 3 lines of code76Vertically align an image inside div76Horizontal and Vertical centering using table layout77Using calc()77

Vertically align dynamic height elements78Using line-height79Centering vertically and horizontally without worrying about height or width79The outer container79The inner container79The content box79Demo80Centering with fixed size80Horizontal centering with only fixed width81Vertical centering with fixed height81Using margin: 0 auto;82Chapter 12: Clipping and -path:85ExamplesClipping (Polygon)8686CSS:86HTML:86Clipping (Circle)87CSS:87HTML87Clipping and Masking: Overview and Difference88Clipping88Masking88Simple mask that fades an image from solid to transparent89CSS89HTML89Using masks to cut a hole in the middle of an image90

CSS90HTML90Using masks to create images with irregular shapes91CSS91HTML91Chapter 13: Colors93Syntax93Examples93Color KeywordsColor Keywords9393Hexadecimal Value100Background100Syntax101rgb() NotationSyntaxhsl() se in same element103Inherited from parent element103rgba() NotationSyntaxhsla() Notation104104105Syntax105Chapter 14: Columns106Syntax106Examples106Simple Example (column-count)106Column Width107Chapter 15: Comments109

Syntax109Remarks109Examples109Single Line109Multiple Line109Chapter 16: s110Applying roman numerals styling to the counter output111CSS111HTML111Number each item using CSS Counter111CSS111HTML112Implementing multi-level numbering using CSS counters112CSS112HTML112Chapter 17: CSS design 114Code example115Chapter 18: CSS Image Sprites116Syntax116Remarks116Examples116A Basic ImplementationChapter 19: CSS Object Model (CSSOM)116118

Remarks118Examples118Introduction118Adding a background-image rule via the CSSOM118Chapter 20: Cursor Styling120Syntax120Examples120Changing cursor type120pointer-events121caret-color121Chapter 21: Custom Properties OWSER SUPPORT / COMPATIBILITY122Examples122Variable Color122Variable Dimensions123Variable Cascading123Valid/Invalids124With media queries125Chapter 22: Feature 127Basic @supports usage127Chaining feature detections127Chapter 23: Filter Property129Syntax129Parameters129Remarks130

Examples130Drop Shadow (use box-shadow instead if possible)130Multiple Filter Values130Hue Rotate131Invert Color132Blur132Chapter 24: Flexible Box Layout er Prefixes134Resources134Examples135Sticky Variable-Height Footer135Holy Grail Layout using Flexbox135Perfectly aligned buttons inside cards with flexbox137Dynamic Vertical and Horizontal Centering (align-items, justify-content)139Simple Example (centering a single element)139HTML139CSS139Reasoning139Individual Property Examples140Example: justify-content: center on a horizontal flexbox140Example: justify-content: center on a vertical flexbox141Example: align-content: center on a horizontal flexbox142Example: align-content: center on a vertical flexbox143Example: Combination for centering both on horizontal flexbox144Example: Combination for centering both on vertical flexbox145Same height on nested containers146Optimally fit elements to their container147Chapter 25: Floats149

Syntax149Remarks149Examples149Float an Image Within Text149Simple Two Fixed-Width Column Layout150Simple Three Fixed-Width Column Layout151Two-Column Lazy/Greedy Layout152clear property153Clearfix154Clearfix (with top margin collapsing of contained floats still occurring)154Clearfix also preventing top margin collapsing of contained floats154Clearfix with support of outdated browsers IE6 and IE7155In-line DIV using float155Use of overflow property to clear floats157Chapter 26: amples158Media print page-breakChapter 27: ) function160attr() function161linear-gradient() function161radial-gradient() function161var() function161Chapter 28: GridIntroduction163163

Remarks163Examples163Basic ExampleChapter 29: Inheritance163165Syntax165Examples165Automatic inheritance165Enforced inheritance165Chapter 30: Inline-Block LayoutExamplesJustified navigation bar167167167HTML167CSS167Notes167Chapter 31: Internet Explorer Hacks169Remarks169Examples169High Contrast Mode in Internet Explorer 10 and greaterExamples169169More Information:169Internet Explorer 6 & Internet Explorer 7 only169Internet Explorer 8 only170Adding Inline Block support to IE6 and IE7170Chapter 32: Layout Control171Syntax171Parameters171Examples172The display property172Inline172Block172Inline Block172

noneTo get old table structure using divChapter 33: Length 6Remarks177Examples177Font size with rem177Creating scalable elements using rems and ems178vh and vw179vmin and vmax179using percent %179Chapter 34: List 81Type of Bullet or Numbering181Bullet Position182Removing Bullets / Numbers182Chapter 35: 184Apply Margin on a Given Side184Direction-Specific Properties184Specifying Direction Using Shorthand Property185Margin Collapsing186Horizontally center elements on a page using margin188

Margin property simplification188Negative margins189Example 1:189Chapter 36: Media 193Basic Example193Use on link tag193mediatype193Using Media Queries to Target Different Screen Sizes194Width vs Viewport195Media Queries for Retina and Non Retina Screens196Terminology and Structure196General Structure of a Media Query196A Media Query containing a Media Type196A Media Query containing a Media Type and a Media Feature197A Media Query containing a Media Feature (and an implicit Media Type of "all")197Media queries and IE8197A Javascript based workaround197The alternative198Chapter 37: Multiple c example199Create Multiple Columns200Chapter 38: Normalizing Browser Styles201Introduction201Remarks201

Examples201normalize.css201What does it do201Difference to reset.css202Approaches and ExamplesChapter 39: Object Fit and hapter 40: Opacity207Syntax207Remarks207Examples207Opacity Property207IE Compatibility for opacity 207Chapter 41: s210Overview210outline-style210Chapter 42: s212overflow: scroll212overflow-wrap213overflow: visible214Block Formatting Context Created with Overflow215overflow-x and overflow-y216

Chapter 43: Padding218Syntax218Remarks218Examples218Padding on a given side218Padding Shorthand219Chapter 44: PerformanceExamplesUse transform and opacity to avoid trigger layout221221221DON'T221DO222Chapter 45: ples223Fixed position223Overlapping Elements with 25Relative Position226Absolute Position226Static positioning226Chapter 46: rs228Remarks228

Examples229Pseudo-Elements229Pseudo-Elements in Lists229Chapter 47: ples231Attribute tribute "value"]233[attribute* "value"]233[attribute "value"]233[attribute "value"]234[attribute "value"]234[attribute "value"]234[attribute "value" i]234Specificity of attribute ndant Combinator: selector selector235Child Combinator: selector selector236Adjacent Sibling Combinator: selector selector236General Sibling Combinator: selector selector237Class Name Selectors237ID selectors238Pseudo-classes239Syntax239

List of pseudo-classes:239Basic selectors242How to style a Range input242Global boolean with checkbox:checked and (general sibling combinator)243Add boolean as a checkbox243Change the boolean's value243Accessing boolean value with CSS243In action244CSS3 :in-range selector example244Child Pseudo Class244Select element using its ID without the high specificity of the ID selector245A. The :not pseudo-class example & B. :focus-within CSS pseudo-class245The :only-child pseudo-class selector example247The :last-of-type selector248Chapter 48: Shapes for 49Shape Outside with Basic Shape – circle()249Shape margin251Chapter 49: Single Element Circles and Ellipses257Circle257Ellipse258Trapezoid258Cube259

PyramidChapter 50: Stacking ContextExamplesStacking ContextChapter 51: Structure and Formatting of a CSS r266Examples266Rules, Selectors, and Declaration Blocks266Property Lists266Multiple Selectors267Chapter 52: 270caption-side270Chapter 53: The Box Model272Syntax272Parameters272Remarks272About padding-boxExamplesWhat is the Box Model?272272272The Edges272Example273

box-sizingChapter 54: xamples277Transition shorthand277Transition (longhand)278CSS278HTML278cubic-bezierChapter 55: amples282Font Size282The Font Shorthand282Font Stacks283Letter Spacing283Text Transform284Text Indent284Text Decoration285Text Overflow285Word Spacing286Text Direction286Font Variant287Quotes288Text Shadow288Shadow without blur radius288Shadow with blur radius288Multiple Shadows288

Chapter 56: Vertical Centering289Remarks289Examples289Centering with display: table289Centering with Transform289Centering with Flexbox290Centering Text with Line Height290Centering with Position: absolute291Centering with pseudo element292Credits293

AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest versionfrom: cssIt is an unofficial and free CSS ebook created for educational purposes. All the content is extractedfrom Stack Overflow Documentation, which is written by many hardworking individuals at StackOverflow. It is neither affiliated with Stack Overflow nor official CSS.The content is released under Creative Commons BY-SA, and the list of contributors to eachchapter are provided in the credits section at the end of this book. Images may be copyright oftheir respective owners unless otherwise specified. All trademarks and registered trademarks arethe property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct noraccurate, please send your feedback and corrections to info@zzzprojects.comhttps://riptutorial.com/1

Chapter 1: Getting started with CSSRemarksStyles can be authored in several ways, allowing for varying degrees of reuse and scope whenthey are specified in a source HTML document. External stylesheets can be reused across HTMLdocuments. Embedded stylesheets apply to the entire document in which they are specified. Inlinestyles apply only to the individual HTML element on which they are specified.VersionsVersionRelease nal StylesheetAn external CSS stylesheet can be applied to any number of HTML documents by placing a link element in each HTML document.The attribute rel of the link tag has to be set to "stylesheet", and the href attribute to therelative or absolute path to the stylesheet. While using relative URL paths is generally consideredgood practice, absolute paths can be used, too. In HTML5 the type attribute can be omitted.It is recommended that the link tag be placed in the HTML file's head tag so that the styles areloaded before the elements they style. Otherwise, users will see a flash of unstyled content.Examplehello-world.html !DOCTYPE html html head meta charset "utf-8" / link rel "stylesheet" type "text/css" href "style.css" /head body h1 Hello world! /h1 https://riptutorial.com/2

p I CSS /p /body /html style.cssh1 {color: green;text-decoration: underline;}p {font-size: 25px;font-family: 'Trebuchet MS', sans-serif;}Make sure you include the correct path to your CSS file in the href. If the CSS file is in the samefolder as your HTML file then no path is required (like the example above) but if it's saved in afolder, then specify it like this href "foldername/style.css". link rel "stylesheet" type "text/css" href "foldername/style.css" External stylesheets are considered the best way to handle your CSS. There's a very simplereason for this: when you're managing a site of, say, 100 pages, all controlled by a singlestylesheet, and you want to change your link colors from blue to green, it's a lot easier to make thechange in your CSS file and let the changes "cascade" throughout all 100 pages than it is to gointo 100 separate pages and make the same change 100 times. Again, if you want to completelychange the look of your website, you only need to update this one file.You can load as many CSS files in your HTML page as needed. link rel "stylesheet" type "text/css" href "main.css" link rel "stylesheet" type "text/css" href "override.css" CSS rules are applied with some basic rules, and order does matter. For example, if you have amain.css file with some code in it:p.green { color: #00FF00; }All your paragraphs with the 'green' class will be written in light green, but you can override thiswith another .css file just by including it after main.css. You can have override.css with thefollowing code follow main.css, for example:p.green { color: #006600; }Now all your paragraphs with the 'green' class will be written in darker green rather than lightgreen.Other principles apply, such as the '!important' rule, specificity, and inheritance.https://riptutorial.com/3

When someone first visits your website, their browser downloads the HTML of the current pageplus the linked CSS file. Then when they navigate to another page, their browser only needs todownload the HTML of that page; the CSS file is cached, so it does not need to be downloadedagain. Since browsers cache the external stylesheet, your pages load faster.Internal StylesCSS enclosed in style /style tags within an HTML document functions like an externalstylesheet, except that it lives in the HTML document it styles instead of in a separate file, andtherefore can only be applied to the document in which it lives. Note that this element must beinside the head element for HTML validation (though it will work in all current browsers if placedin body). head style h1 {color: green;text-decoration: underline;}p {font-size: 25px;font-family: 'Trebuchet MS', sans-serif;} /style /head body h1 Hello world! /h1 p I CSS /p /body Inline StylesUse inline styles to apply styling to a specific element. Note that this is not optimal. Placing stylerules in a style tag or external CSS file is encouraged in order to maintain a distinction betweencontent and presentation.Inline styles override any CSS in a style tag or external style sheet. While this can be useful insome circumstances, this fact more often than not reduces a project's maintainability.The styles in the following example apply directly to the elements to which they are attached. h1 style "color: green; text-decoration: underline;" Hello world! /h1 p style "font-size: 25px; font-family: 'Trebuchet MS';" I CSS /p Inline styles are generally the safest way to ensure rendering compatibility across various emailclients, programs and devices, but can be time-consuming to write and a bit challenging tomanage.CSS @import rule (one of CSS at-rule)The @import CSS at-rule is used to import style rules from other style sheets. These rules musthttps://riptutorial.com/4

precede all other types of rules, except @charset rules; as it is not a nested statement, @importcannot be used inside conditional group at-rules. @import.How to use @importYou can use @import rule in following ways:A. With internal style tag style @import url('/css/styles.css'); /style B. With external stylesheetThe following line imports a CSS file named additional-styles.css in the root directory into theCSS file in which it appears:@import '/additional-styles.css';Importing external CSS is also possible. A common use case are font files.@import 'https://fonts.googleapis.com/css?family Lato';An optional second argument to @import rule is a list of media queries:@import '/print-styles.css' print;@import url('landscape.css') screen and (orientation:landscape);Changing CSS with JavaScriptPure JavaScriptIt's possible to add, remove or change CSS property values with JavaScript through an element'sstyle property.var el y 0.5;el.style.fontFamily 'sans-serif';Note that style properties are named in lower camel case style. In the example you see that thecss property font-family becomes fontFamily in javascript.As an alternative to working directly on elements, you can create a style or link element inJavaScript and append it to the body or head of the HTML document.jQueryhttps://riptutorial.com/5

Modifying CSS properties with jQuery is even simpler. ('#element').css('margin', '5px');If you need to change more than one style rule: ('#element').css({margin: "5px",padding: "10px",color: "black"});jQuery includes two ways to change css rules that have hyphens in them (i.e. font-size). You canput them in quotes or camel-case the style rule name. ('.example-class').css({"background-color": "blue",fontSize: "10px"});See also JavaScript documentation – Reading and Changing CSS Style. jQuery documentation – CSS ManipulationStyling Lists with CSSThere are three different properties for styling list-items: list-style-type, list-style-image, andlist-style-position, which should be declared in that order. The default values are disc, outside,and none, respectively. Each property can be declared separately, or using the list-styleshorthand property.list-style-typedefines the shape or type of bullet point used for each list-item.Some of the acceptable values for list-style-type: For an exhaustive list, see the W3C specification wiki)To use square bullet points for each list-item, for example, you would use the following propertyvalue pair:https://riptutorial.com/6

li {list-style-type: square;}The list-style-image property determines whether the list-item icon is set with an image, andaccepts a value of none or a URL that points to an image.li {list-style-image: url(images/bullet.png);}The list-style-position property defines where to position the list-item marker, and it accepts oneof two values: "inside" or "outside".li {list-style-position: inside;}Read Getting started with CSS online: ted-with-csshttps://riptutorial.com/7

Chapter 2: 2D TransformsSyntax Rotate Transformtransform: rotate( angle )Translate Transformtransform: translate( length-or-percentage [, length-or-percentage ]?)transform: translateX( length-or-percentage )transform: translateY( length-or-percentage )Skew Transformtransform: skew( angle [, angle ]?)transform: skewX( angle )transform: skewY( angle )Scale Transformtransform: scale( scale-factor [, scale-factor ]?)transform: scaleX( scale-factor )transform: scaleY( scale-factor )Matrix Transformtransform: matrix( number [, number )Defines a transformation that moves the element around a fixed pointon the Z axistranslate(x,y)Moves the position of the element on the X and Y axistranslateX(x)Moves the position of the element on the X axistranslateY(y)Moves the position of the element on the Y axisscale(x,y)Modifies the size of the element on the X and Y axisscaleX(x)Modifies the size of the element on the X axisscaleY(y)Modifies the size of the element on the Y axisskew(x,y)Shear mapping, or transvection, distorting each point of an elementby a certain angle in each directionskewX(x)Horizontal shear mapping distorting each point of an element by acertain angle in the horizontal directionhttps://riptutorial.com/8

Function/ParameterDetailsskewY(y)Vertical shear mapping distorting each point of an element by acertain angle in the vertical directionmatrix()Defines a 2D transformation in the form of a transformation matrix.angleThe angle by which the element should be rotated or skewed(depending on the function with which it is used). Angle can beprovided in degrees (deg), gradians (grad), radians (rad) or turns (turn). In skew() function, the second angle is optional. If not provided,there will be no (0) skew in Y-axis.length-or-percentageThe distance expressed as a length or a percentage by which theelement should be translated. In translate() function, the secondlength-or-percentage is optional. If not provided, then there would beno (0) translation in Y-axis.scale-factorA number which defines how many times the element should bescaled in the specified axis. In scale() function, the second scalefactor is optional. If not provided, the first scale-factor will be appliedfor Y-axis also.Remarks2D Coordiante systemTransforms are made according to a 2D X/Y coordiante system. The X axis goes from right to leftand the Y axis goes downwards as shown in the following image:So a positive translateY() goes downwards and a positive translateX() goes right.https://riptutorial.com/9

Browser support and prefixes IE supports this property since IE9 with the -ms- prefix. Older versions and Edge don't needthe prefix Firefox supports it since version 3.5 and needs the -moz- prefix until version 15 Chrome since version 4 and until version 34 needs the -webkit- prefix Safari needs the -webkit- prefix until version 8 Opera needs the -o- prefix for version 11.5 and the -webkit- prefix from version 15 to 22 Android needs the -webkit- prefix from version 2.1 to 4.4.4Example of prefixed transform:-webkit-transform: rotate(45deg);-ms-transform: rotate(45deg);transform: rotate(45deg);ExamplesRotateHTML div class "rotate" /div CSS.rotate {width: 100px;height: 100px;background: teal;transform: rotate(45deg);}This example will rotate the div by 45 degrees clockwise. The center of rotation is in the center ofthe div, 50% from left and 50% from top. You can change the center of rotation by setting thetransform-origin property.transform-origin: 100% 50%;The above example will set the center of rotation to the middle of the right side end.ScaleHTML div class "scale" /div https://riptutorial.com/10

CSS.scale {width: 100px;height: 100px;background: teal;transform: scale(0.5, 1.3);}This example will scale the div to 100pxthe Y axis.* 0.5 50pxon the X axis and to 100px* 1.3 130pxonThe center of the transform is in the center of the div, 50% from left and 50% from top.TranslateHTML div class "translate" /div CSS.translate {width: 100px;height: 100px;background: teal;transform: translate(200px, 50%);}This example will move the div by 200px on the X axis and by 100px* 50% 50pxon the Y axis.You can also specify translations on a single axis.On the X axis:.translate {transform: translateX(200px);}On the Y axis:.translate {transform: translateY(50%);}SkewHTML div class "skew" /div https://riptutorial.com/11

CSS.skew {width: 100px;height: 100px;background: teal;transform: skew(20deg, -30deg);}This example will skew the div by 20 degrees on the X axis and by - 30 degrees on the Y axis.The center of the transform is in the center of the div, 50% from left and 50% from top.See the result here.Multiple transformsMultiple transforms can be applied to an element in one property like this:transform: rotate(15deg) translateX(200px);This will rotate the element 15 degrees clockwise and then translate it 200px to the right.In chained transforms, the coordinate system moves with the element. This means that thetranslation won't be horizontal but on an axis rotate 15 degrees clockwise as shown in thefollowing image:https://riptutorial.com/12

Changing the order of the transforms will change the output. The first example will be different totransform: translateX(200px) rotate(15deg); div class "transform" /div .transform {transform: rotate(15deg) translateX(200px);}As shown in this image:Transform OriginTransformations are done with respect to a point which is defined by the transform-origin property.The property takes 2 values : transform-origin:X Y;In the following example the first div (.tl) is rotate around the top left corner with transform-origin:0 0; and the second (.tr)is transformed around it's top right corner with transform-origin: 100% 0.The rotation is applied on hover :HTML:https://riptutorial.com/13

div class "transform originl" /div div class "transform origin2" /div CSS:.transform {display: inline-block;width: 200px;height: 100px;background: teal;transition: transform 1s;}.origin1 {transform-origin: 0 0;}.origin2 {transform-origin: 100% 0;}.transform:hover {transform: rotate(30deg);}The default value for the transform-origin property is 50%50%which is the center of the element.Read 2D Transforms online: shttps://riptutorial.com/14

Chapter 3: 3D TransformsRemarksCoordinate system3D transforms are made according to an (x,y, z)coordinate vector system in Euclidean space.The following image shows an example of coordinates in Euclidean space:In CSS, The x axis represents the horizontal (left and right) The y axis represents the vertical (up and down) The z axis represents the depth (forward and backward/closer and further)The following image shows how these coordinates are translated in CSS:Exampleshttps://riptutorial.com/15

3D cube3D transforms can be use to create many 3D shapes. Here is a simple 3D CSS cube example:HTML: div class "cube" div class "cubeFace" /div div class "cubeFace face2" /div /div CSS:body {perspective-origin: 50% 100%;perspective: 1500px;overflow: hidden;}.cube {position: relative;padding-bottom: 20%;transform-style: preserve-3d;transform-origin: 50% 100%;transform: rotateY(45deg) rotateX(0);}.cubeFace {position: absolute;top: 0;left: 40%;width: 20%;height: 100%;margin: 0 auto;transform-style: inherit;background: #C52329;box-shadow: inset 0 0 0 5px #333;transform-origin: 50% 50%;transform: rotateX(90deg);

CSS 111 HTML 111 Number each item using CSS Counter 111 CSS 111 HTML 112 Implementing multi-level numbering using CSS counters 112 CSS 112 HTML 112 Chapter 17: CSS design patterns 114 Introduction 114 Remarks 114 Examples 114 BEM 114 Code example 115 Chapter 18: CSS Image Sprites 116 Synta