Lucas Santos
Lucas Santos

Reputation: 1369

Can you use 2 :before pseudo classes in the same div?

Lets say I have:

<div class="container">
<p>blah blah blah</p>
</div>

would I be able to use 2 :before pseudo classes in that same container div?

like so:

  .container:before{
    content: " ";
    position: absolute;
    top: 0;
    left: 0;
    width: 31%;
    height: 61%;
    background-color: black;
  }

.container:before{
    content: " A String ";
    position: absolute;
    top: 0;
    left: 0;
    background-color: black;
  }

Ignore the actual css but the question here is would that be valid inserting 2 pseudo classes before that container div? and if not is there a way that it can be?

Upvotes: 0

Views: 3305

Answers (2)

Polynomial Proton
Polynomial Proton

Reputation: 5135

It cannot be done, since the css is overwritten, you can see the same here Also Amar Syla answered the same

if not is there a way that it can be?

You can use java script/ jquery to add a class or an id to the div based on your condition and the set the css.

For example:

#before1.container{
    content: " ";
    position: absolute;
    top: 0;
    left: 0;

    background-color: red;
  }

#before.container{
    content: " A String ";
    position: absolute;
    top: 100px;
    left: 0;
    background-color: green;
  }

Then you just need to set the id like below, using jquery/javascript

<div id="before" class="container">
<p>blah blah blah</p>
</div>


<div id="before1" class="container">
<p>blah blah blah</p>
</div>

To know how to set div id dynamically, check this link It has both java script and jquery solutions

Upvotes: 0

Amar Syla
Amar Syla

Reputation: 3643

No, you can't use two :before instanced in a single element. Here is a non-working jsfiddle, which makes use of two :before instances on a single div. As you can see, the second :before statement overrides the first one's styles.

http://jsfiddle.net/Luwhf700/

Now, here, we have a working one, using :before and :after, which would be similar to using two :before statements (only for absolute positioning elements).

http://jsfiddle.net/Luwhf700/1/

Upvotes: 3

Related Questions