Cut word with CSS

Asked

Viewed 56 times

2

I have the following div.

<span class="credit-font" id="valYearCD">2036</span>

I need the content from within 2036 to be reduced, and whatever content appears within that div, show only the last two numbers, in which case it would be only 36.

You can do this with CSS or Jquery?

3 answers

2

You can do it this way (explanations in the code):

$(document).ready(function(){      // DOM carregado
   var elm = $("#valYearCD");      // elemento
   var txt = elm.text();           // texto do elemento
   var fim = txt.match(/\d{2}\b/); // pega os 2 últimos algarismos
   elm.text(fim);                  // altera o texto do elemento
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="credit-font" id="valYearCD">2036</span>

  • It only changes the click? It can come by default already?

  • Just change the function of onclick for onload for example.

  • @Felipegoulart Altered!

  • @Felipegoulart I put the button with just click to illustrate

2


Guy like you put CSS in the question tag I’ll answer you with CSS only.

Notice that the main point here is to use the width with the size in CH (Character). Then a width:2ch would be the width of 2 caractéres.

Option 1:

Using direction:rtl and overflow:hidden in the parent you align the text to the right in a "window" in the box with 2ch width. Need almost nothing of css.

.box {
    width: 2ch;
    background-color: #f00;
    direction: rtl;
    overflow: hidden;
    font-size:3rem;
}
<div class="box">
  <span class="credit-font" id="valYearCD">2036</span>
</div>


Option 2:

With this in mind you can only cover the first two digits with one element ::after for example.

OBS: Note that it is only a css for any font size, because regardless of the font size the red box width is always 2ch

span {
    display: inline-block;
    width: 4ch;
    position: relative;
}
span::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 2ch;
    background-color: #f00;
}
<span class="credit-font" id="valYearCD">2036</span>
        <br><br>
        <span style="font-size: 3rem;" class="credit-font" id="valYearCD">2036</span>
        <br><br>
        <span style="font-size: 6rem;" class="credit-font" id="valYearCD">2036</span>

  • Great, it worked. But, I saw that it keeps the space of the first two numbers.

  • @Felipegoulart in Option 1 it cuts everything even, in option 2 it leaves the characters still on the screen, I suggest using the Option 1

0

Friend you can use jquery’s text() function to take text and substr() to leave only the last two numbers:

$('#valYearCD').text($('#valYearCD').text().substr($('#valYearCD').text().length - 2, $('#valYearCD').text().length));

This way will show only the last 2 numbers of your text.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.