Tailwind CSS Top/Right/Bottom/Left
Tailwind CSS provides a set of utility classes to easily position an element with respect to its containing element.
Syntax
The classes for positioning an element are:
top-<size>
: Positions an element from the top of its containing element.right-<size>
: Positions an element from the right of its containing element.bottom-<size>
: Positions an element from the bottom of its containing element.left-<size>
: Positions an element from the left of its containing element.
In the syntax, <size>
can be any of the following:
0
: Refers to0px
.auto
: Refers to the default value of the CSS property for the element.px
: Refers to a fixed number of pixels.full
: Refers to the full width or height of the containing element, depending on the direction.
Example
Here's an example that demonstrates the use of the top/right/bottom/left classes to position an element:
<div class="relative h-24 w-24">
<div class="absolute top-0 left-0 h-full w-full bg-blue-500"></div>
<div class="absolute bottom-0 right-0 h-full w-full bg-green-500"></div>
</div>
In this example, the .relative
class is used to specify the containing element for the two absolutely positioned <div>
elements. The .absolute
class is used to position the elements relative to their containing element.
Output
The above example will show two rectangles of blue
and green
colors positioned on opposite corners of the relative
container like this:
Explanation
- The
.relative
class specifies a container element, with the.h-24
and.w-24
classes setting its height and width. - The
.absolute
class specifies the position of each<div>
element inside the container.
The top-0
and left-0
classes set the position of the blue rectangle to the top left of the container, while bottom-0
and right-0
classes set the position of the green rectangle to the bottom right of the container. The .h-full
and .w-full
classes cause the rectangles to take up the full height and width of the container, respectively.
Use
Use the top/right/bottom/left classes to position elements relative to their containing element. These classes can be used with any HTML element, including <img>
and <svg>
.
Important Points
- The
.relative
class should be used to specify the containing element for any elements that need to be positioned absolutely. - The
.absolute
class should be used to specify the position of an element with respect to its containing element. - Use the
<size>
values to adjust the position of an element based on the distance from the top/right/bottom/left edge of the containing element.
Summary
The top/right/bottom/left classes in Tailwind CSS are a set of utility classes that make it easy to position HTML elements relative to their containing element. These classes can be used to align an element exactly where you want it on the page, and can be combined with other classes to style the element's appearance.