Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat an item multiple times in HTML or CSS?

Tags:

html

css

I need to place a star, ★, on a Web page, repeatedly. Is there a way to specify a symbol and how many times it should appear, in HTML or CSS? E.g., something like this, but not necessarily the same syntax, in which an item is specified, along with a quantity:

<repeat n="5">★</repeat>

This will result in:

★★★★★
like image 722
Village Avatar asked Jan 27 '14 08:01

Village


3 Answers

You could place the star as a repeating background image of an element; and tweak the width of the element via CSS. Something like:

.stars {
  display: inline-block;
  width: 13px;
  height: 13px;
  background-image: url(https://i.stack.imgur.com/KaEDC.png);
}
.stars-2 {
  width: 26px;
}
.stars-3 {
  width: 39px;
}
.stars-4 {
  width: 52px;
}
.stars-5 {
  width: 65px;
}
<span class="stars"></span><br>
<span class="stars stars-2"></span><br>
<span class="stars stars-3"></span><br>
<span class="stars stars-4"></span><br>
<span class="stars stars-5"></span>
like image 56
Salman A Avatar answered Oct 22 '22 04:10

Salman A


Use content property like this:

Note: that using repeat is not recommended in your case its not a valid html tag, use div, span or a.

Demo

Use SCSS or LESS to generate style sheet like this.

CSS:

<style>
repeat {
    display:block;
}

repeat[n="1"]:before {
   content: "★";
}

repeat[n="2"]:before {
   content: "★★";
}

repeat[n="3"]:before {
   content: "★★★";
}

repeat[n="4"]:before {
   content: "★★★★";
}

repeat[n="5"]:before {
   content: "★★★★★";
}
</style>

HTML:

<repeat n="1"></repeat>
<repeat n="2"></repeat>
<repeat n="5"></repeat>
like image 30
Waqar Alamgir Avatar answered Oct 22 '22 06:10

Waqar Alamgir


If you are willing to use jQuery (or just javascript but different code), you could do:

$(document).ready(function() {
  $('[repeat]').each(function() {
     var toRepeat = $(this).text();
     var times = parseInt($(this).attr('repeat'));
     var repeated = Array(times+1).join(toRepeat);
     $(this).text(repeated).removeAttr('repeat');
   });
 });

Then when you have

<span repeat="5">★</span>

It will become

<span>★★★★★</span>
like image 31
dave Avatar answered Oct 22 '22 06:10

dave