This tutorial aims to explain the concepts of Display and Position properties in CSS. By the end of this tutorial, you will be able to understand and effectively use the Display and Position properties in CSS to control the layout and flow of elements on a webpage.
What you'll learn:
The concept of the Display property
The different values of the Display property
The concept of the Position property
The different values of the Position property
Practical examples of how to use these properties
Prerequisites:
Basic knowledge of HTML
Basic understanding of CSS
2. Step-by-Step Guide
Display Property
The Display property in CSS determines the type of the box that an element should generate. It has several values:
Block: Elements like div, h1, p, etc. are block elements. They take up the full width available, with a new line before and after.
Inline: Elements like span, a, img, etc. are inline elements. They take up only as much width as necessary and do not start on a new line.
None: This value causes an element to not appear on the page at all. Any space that the element would have taken up is also removed.
Position Property
The Position property in CSS specifies how an element is positioned in a document. It has several values:
Static: This is the default value. Elements are positioned according to the normal flow of the page.
Relative: Elements are positioned relative to their normal position.
Absolute: Elements are positioned relative to the nearest positioned ancestor.
Fixed: Elements are positioned relative to the viewport.
Sticky: Elements are positioned based on the user's scroll position.
3. Code Examples
Display Property
/* This will make the div behave like an inline element */
div {
display: inline;
}
Position Property
/* This will position the element 20px from the top and 10px from the right of its normal position */
div {
position: relative;
top: 20px;
right: 10px;
}
4. Summary
In this tutorial, we've learned about two important CSS properties: Display and Position. Display controls the type of box an element should generate and Position determines how an element is positioned in a document. You can manipulate these properties to control the layout and flow of your webpages.
5. Practice Exercises
Exercise 1: Create a webpage with 5 div elements. Use the display property to arrange them in a single line.
Exercise 2: Position an element 50px from the top of the page and 100px from the left edge of the page.
Exercise 3: Hide an element from the page using the display property.
Solutions
Use the display: inline-block; property to arrange the div elements in a line.
Use the position: absolute; property along with top: 50px; and left: 100px; to position the element.
Use the display: none; property to hide the element from the page.
Remember, practice is key to mastering these properties. So, keep experimenting with different values and observe the changes. Happy coding!