user4258918
user4258918

Reputation:

How to add a border outside of element with ::before selector?

This is what I'm trying to build.

Basically, I want to add the purple border for the selected item. I think the ::before pseudo element is the best option here?

I've tried this, but it's not very good at all and it sits right next to the text rather than on the edge of the screen:

#serverList {
  li::before {
    content: 'a';
    height: 5em;
    width: 1em;
    color: blue;
    background-color: blue;
  }
}

(this is the result)

Thank you!

Upvotes: 1

Views: 570

Answers (2)

vtolentino
vtolentino

Reputation: 784

What about the following? You can use a wrapper and add your content inside of a span which is centered.

.wrapper {
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;
  padding: 12px 12px 12px 40px;
}

.wrapper::before {
  content: '';
  left: 0;
  width: 10px;
  height: 100%;
  opacity: 0;
  background: lightblue;
  position: absolute;
  transition: 0.5s all ease;
  border-top-right-radius:10px;
  border-bottom-right-radius:10px;
}

.wrapper:hover::before {
  opacity: 1; 
}
<div class="wrapper">
  <span>This is a text</span>
</div>
<div class="wrapper">
  <span>This is a second text</span>
</div>
<div class="wrapper">
  <span>This is another</span>
</div>

EDIT #1

If you want to retain the state:

$( ".wrapper" ).each(function(index) {
    $(this).on("click", function(){
       $(this).toggleClass("active");
    });
})
.wrapper {
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;
  padding: 12px 12px 12px 40px;
  box-shadow: 0px 0px 1px grey;
  margin-bottom: 6px;
  max-width: 200px;
}

.wrapper::before {
  content: '';
  left: 0;
  width: 10px;
  height: 100%;
  opacity: 0;
  background: lightblue;
  position: absolute;
  transition: 0.5s all ease;
  border-top-right-radius:10px;
  border-bottom-right-radius:10px;
}

.wrapper.active::before {
  opacity: 1; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <span>Click here</span>
</div>
<div class="wrapper">
  <span>Click here 2</span>
</div>
<div class="wrapper">
  <span>Click here 3</span>
</div>

Upvotes: 0

pll
pll

Reputation: 21

First, you have to add position relative to father element:

 #serverList li{
    position: relative;
  }

Then, let's work in children element(::before)

 #serverList li::before{
    content: '';  /* is not necesary any info here */
    height: 5em;
    width: 1em;
    color: blue;
    background-color: blue;
    position: absolute; /* this is absolute to the father element*/
    left: 0; /* we want this in the point 0 of our father element*/
   }

You can play with properties top, left, right, bottom and the position absolute.

Upvotes: 2

Related Questions