I am trying to achieve this via scss
a title with a clored background
I tried adding : before with colored bacground
and also I tried making one div relative and the other one position: aboslute
b ut it didn’t work
html:
` <div class="volunteer__title">
<div class="volunteer__title--bg">
<div class="volunteer__title--text" >Volunteer</div>
</div>`
css:
&__title {
display: flex;
flex-direction: row;
font-family: "Fredoka", sans-serif;
font-size: 30px;
position: relative;
&--bg {
background-color: $darkGreen;
width: 100px;
height: 25px;
border-radius: 5px;
&--text {
position: fixed;
left: 0;
top: 0;
}
}
}
but didn’t work
any ideas?
2
Answers
I made a change using
display
property, fromfixed
toabsolute
.Fixed Positioning:
When an element is set to
position: fixed;
it is positioned relative to the browser window’s viewport, regardless of scrolling. This means that even if the user scrolls the page, the element will stay in the same position on the screen. Fixed elements are often used for headers, footers, or navigation bars that need to remain visible at all times.Absolute Positioning:
On the other hand, when an element is set to
position: absolute;
it is positioned relative to its closest positioned ancestor (an element with a position value other than static) or the document’s initial containing block if no positioned ancestor is found. Absolute positioning takes the element out of the normal document flow, allowing you to precisely position it anywhere on the page. When the page is scrolled, absolute positioned elements will move with their positioned ancestor.I mixed
display: absolute;
andz-index: -1;
(check the code below).Check
width: fit-content
involunteer__title
as well.Example 1
In SCSS:
Example 2
In this example, I get rid of the element
bg
and used::after
that creates a pseudo-element of the selected element (text
).In SCSS:
For more details about these properties, check the links below:
CSS Tricks | Absolute, Relative, Fixed Positioning
MDN | z-index
MDN | ::after
While @001 was on the right track, there are some changes to be made to add responsivness and to simplyfy the entire case.
First at all you should not use an HTML element to create the green box but a pseudo-element by using either
::before
ore::after
and then position it withposition: absolute
in relative units.If you want it in SASS you can use combi9ne it into: