Antutu Cat
Antutu Cat

Reputation: 105

CSS ::first-letter pseudo-elements

I'm trying to do this using only this <div>1 Hello, Welcome To Elzero Web School</div>

enter image description here

I tried but I can't figure it out that is my code :

div{
    position: relative;
    background-color: rgb(146, 141, 141);
    width: 400px;
    height: 50px;
}
div::first-letter {
    background-color: red;
    font-size: 40px;
    color: white;
    position: absolute;
    left: -25px;
  }

Upvotes: 0

Views: 515

Answers (2)

Abhinav Bhutani
Abhinav Bhutani

Reputation: 176

Note: The ::first-letter pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-letter pseudo- element:

  • font properties
  • color properties
  • background properties
  • margin properties
  • padding properties
  • border properties
  • text-decoration
  • vertical-align (only if "float" is "none")
  • text-transform
  • line-height
  • float
  • clear

source- https://www.w3schools.com/css/css_pseudo_elements.asp

That is why position is not working for the pseudo-element and in order to align the first-letter you can use margin properties to align it outside of your box

I tried to replicate design as close as possible you can take idea from the snippet to position the first-letter

div{
    padding:25px;
    background-color: #d3d3d3;
    font-size: 20px;
    border:20px solid white;
    display:inline-block;
}
div::first-letter {
    background-color: red;
    font-size: 20px;
    color: white;
    padding:15px;
    font-weight:900;
    margin-left:-40px;
    margin-right:10px;
  }
<div>1 Hello, Welcome To Elzero Web School</div>

Upvotes: 1

Fin
Fin

Reputation: 29

You can't change the position of the ::first-letter selector. Here's a list of what you can change with it

  • font properties
  • color properties
  • background properties
  • margin properties
  • padding properties
  • border properties
  • text-decoration
  • vertical-align (only if float is 'none')
  • text-transform (this controls text capitalization)
  • line-height
  • float
  • clear

I'd suggest trying another approach

Upvotes: 0

Related Questions