webta.st.ic
webta.st.ic

Reputation: 5169

Add a second element to div with :after

Hi I've got follow div:

.box {
  width: 100px;
  height: 20px;
  border: 1px solid black;
}
.box:after {
  content: '';
  width: 20px;
  height: 20px;
  background-color: blue;
}
<div class="box"></div>

I would like to add a second div to the .box with pseudo class after. I thought it would work like this, but nothing happens. It should look like this:

enter image description here

How to do this with after?

Thanks.

Upvotes: 1

Views: 84

Answers (3)

Mohammad Usman
Mohammad Usman

Reputation: 39322

.box {
  width: 100px;
  height: 20px;
  position: relative;
  border: 1px solid black;
}
.box:after {
  content: '';
  width: 20px;
  bottom: -1px;
  right: -21px;
  top: -1px;
  position: absolute;
  background-color: blue;
}
<div class="box"></div>

Upvotes: 1

Kiss
Kiss

Reputation: 976

You're code is right, the only thing missing is the property display to that element. Just add a display: block on the :after element. To easily manipulate the pseudo-element, make the main element position: relative, then the :after as position: absolute and place it based on the .box div, something like this :

.box {
  width: 100px;
  height: 20px;
  border: 1px solid black;
  position: relative; /* Made it relative */
}
.box:after {
  content: '';
  position: absolute;
  display: block;
  width: 20px;
  height: 20px;
  border: 1px solid blue;
  top: -1px; /* To compensate the border on the main element */
  background-color: blue;
  left: 100%; /* To place it after the main element */
}

If you truly need another div, try adding some javascript, like this

$(document).ready(function() {
    $('.box').append('<div class="another-box"></div>');
});

Upvotes: 1

Head In Cloud
Head In Cloud

Reputation: 2051

Try This

.box {
  width: 100px;
  height: 20px;
  border: 1px solid black;
}
.box:after {
  content: '';
  width: 20px;
  height: 20px;
  background-color: blue;
  display:block;
  float:right;
}
<div class="box"></div>

Upvotes: 1

Related Questions