
Image by CreativeMagic from pixabay
DESCRIPTION
Use a combination of position relative and absolute to place text on the image (cute cat included) card.
Preview
Combination of positions
x
.container {
position: relative;
margin: 0 auto;
}
.title {
position: absolute;
top: 5%;
left: 50%;
transform: translate(-50%);
margin: 0;
color: #fff;
}
.catImage {
width: 100%;
height: auto;
}
- Position
relative
is used on.container
class to place content relatively to it. - Position
absolute
is used on.title
class withtop
,left
, andtransform
properties. - More about centering on CSS-TRICKS.
- More about positions in CSS on w3schools.
xxxxxxxxxx
<div class="container">
<img src="https://cataas.com/cat/cute" class="catImage" />
<h2 class="title">I'm cute</h2>
</div>
- First, we wrap everything with
div class="container"
. - Then, we render our cute cat image with
<img src.../>
. - Lastly,
h2
has a.title
class which is positioned absolutely. - The above
h2
element will look for the closest container that has arelative
orabsolute
position which is ourdiv
with.container
class and position absolutely to it.
Summary
- Understanding CSS positions is a crucial aspect to succeed in creating application layouts.
- Transforms can be useful for centering content vertically or horizontally.
- Never skip your CSS day as it'll hit you earlier than you think. 😅