Bagzli
Bagzli

Reputation: 6579

Circle background on an input element

I am trying to figure out if this is even possible, from all my research it doesn't appear to be, but I wanted to be 100% sure.

I am trying to draw a circle inside an input element. The circle would be red colour and then when it passes validation it would turn to green. I can do this fairly easy using an image, but I am trying to see if I can avoid using images to do this.

I can easily draw circles with divs:

<div></div>
div{
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: red;
}

but I don't know how to draw a circle on a background element. I was looking into maybe using :before or :after element but that doesn't seem possible.

Are there any ways of accomplishing this?

Upvotes: 2

Views: 5485

Answers (2)

Harry
Harry

Reputation: 89770

You can achieve this using radial-gradient background image like in the below snippet. There is no need to add extra elements as long as you have to support only the modern browsers. Pseudo's won't work with input element because it is a self-closing tag.

Tested and found to be working fine in Chrome(v51.0.2704.19 dev-m), Firefox (v45.0.2), Opera (v36) Edge, IE11, IE10. This approach would not work in IE9 and lower because support for CSS gradients is not there in those browsers.

input {
  background-image: radial-gradient(circle at center, red 4px, transparent 5px);
  background-repeat: no-repeat;
  background-size: 20px 100%; /* equal to the height */
  height: 20px;
  padding-left: 20px; /* equal to background-size in X-axis */
}
input:valid {
  background-image: radial-gradient(circle at center, green 4px, transparent 5px);
}
<input type='text' required/>
<input type='text' value='Some text' required/>

Upvotes: 3

Nenad Vracar
Nenad Vracar

Reputation: 122077

You could use pseudo-element and toggle color with JQuery on validation (i used focus for demo(

$('input').on('focus', function() {
  $(this).parent('div').addClass('active');
});
$('input').on('blur', function() {
  $(this).parent('div').removeClass('active');
});
div {
  position: relative;
}
div:before {
  content: '';
  position: absolute;
  left: 5px;
  top: 50%;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: blue;
  transform: translateY(-50%);
}
div.active:before {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text">
</div>

Upvotes: 1

Related Questions