Czy można zastosować CSS do połowy znaku?

Czego szukam:

Sposób na stylizację jednej połowy znaku. (W tym przypadku połowa litery jest przezroczysta)

Czego aktualnie szukałem i próbowałem (bez powodzenia):

  • metody stylizacji połowy znaku / litery
  • Stylizacja części znaku za pomocą CSS lub JavaScript
  • Zastosuj CSS do 50% znaku

Poniżej przykład tego, co staram się / align = "left" /

x

Czy istnieje do tego rozwiązanie CSS lub JavaScript, czy będę musiał uciekać się do obrazów? Wolałbym nie iść ścieżką obrazu, ponieważ ten tekst będzie generowany dynamicznie.


UPDATE:

Ponieważ wielu pytało, dlaczego miałbym kiedykolwiek chcieć stylizować połowę postaci, właśnie dlatego. Moje miasto niedawno wydało $250,000, aby zdefiniować nową "markę" dla siebie. To logo tak wymyślili. Wiele ludzie narzekali na prostotę i brak kreatywności i nadal to robią. Moim celem było wymyślenie tego Strona WWW dla żartu. Wpisz "Halifax", a zobaczysz, co mam na myśli. :)

Author: Jack Giffin, 2014-05-09

18 answers

Teraz na GitHub jako Plugin!

Tutaj wpisz opis obrazkaZapraszam do rozwidlenia i poprawy.

Demo | Pobierz Zip | Half-Style.com (przekierowanie na GitHub)


  • czysty CSS dla pojedynczego znaku
  • JavaScript używany do automatyzacji tekstu lub wielu znaków
  • zachowuje dostępność tekstu dla czytników ekranu dla niewidomych lub wizualnych zaburzenia

Część 1: Podstawowa Rozwiązanie

Połowa stylu na tekście

Demo: http://jsfiddle.net/arbel/pd9yB/1694/


Działa to na dowolnym dynamicznym tekście lub pojedynczym znaku i jest zautomatyzowane. Wszystko, co musisz zrobić, to dodać klasę do tekstu docelowego, a reszta jest załatwiona.

Również dostępność oryginalnego tekstu jest zachowana dla czytników ekranu dla osób niewidomych i słabowidzących.

Wyjaśnienie dla pojedynczego znaku:

Czysty CSS. Wszystko, co musisz zrobić, to zastosować klasę .halfStyle do każdego elementu, który zawiera znak, który chcesz mieć w połowie stylizowany.

Dla każdego elementu span zawierającego znak, możesz utworzyć atrybut data, na przykład tutaj data-content="X" , a na pseudo elemencie użyj content: attr(data-content);, więc klasa .halfStyle:before będzie dynamiczna i nie będziesz musiał jej kodować dla każdej instancji.

Wyjaśnienie dla dowolnego tekstu:

Wystarczy dodać textToHalfStyle klasę do elementu zawierającego tekst.


// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
.halfStyle {
    position: relative;
    display: inline-block;
    font-size: 80px; /* or any font size will work */
    color: black; /* or transparent, any color */
    overflow: hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
}

.halfStyle:before {
    display: block;
    z-index: 1;
    position: absolute;
    top: 0;
    left: 0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

(jsfiddle demo )


Część 2: zaawansowane rozwiązanie-niezależne od lewej i prawej części

Połowa stylu na tekst-zaawansowane - z cieniem tekstu

dzięki temu rozwiązaniu można stylizować lewe i prawe części, indywidualnie i niezależnie.

Wszystko jest takie samo, tylko bardziej zaawansowany CSS robi magię.

jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
        $el = $(el);
        text = $el.text();
        chars = text.split('');

        // Set the screen-reader text
        $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

        // Reset output for appending
        output = '';

        // Iterate over all chars in the text
        for (i = 0; i < chars.length; i++) {
            // Create a styled element for each character and append to container
            output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
        }

        // Write to DOM only once
        $el.append(output);
    });
});
.halfStyle {
    position: relative;
    display: inline-block;
    font-size: 80px; /* or any font size will work */
    color: transparent; /* hide the base character */
    overflow: hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
}

.halfStyle:before { /* creates the left part */
    display: block;
    z-index: 1;
    position: absolute;
    top: 0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #f00; /* for demo purposes */
    text-shadow: 2px -2px 0px #af0; /* for demo purposes */
}

.halfStyle:after { /* creates the right part */
    display: block;
    direction: rtl; /* very important, will make the width to start from right */
    position: absolute;
    z-index: 2;
    top: 0;
    left: 50%;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #000; /* for demo purposes */
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

(JSFiddle demo)



Część 3: Mix-Match i poprawić

Teraz, kiedy wiemy, co jest możliwe, stwórzmy pewne wariacje.

- Półbuty Poziome

  • Bez Cienia Tekstu:

    Poziome Pół Części - Brak Cienia Tekstu

  • Możliwość cienia tekstu dla każdej pół części niezależnie:

    halfStyle-poziome pół części - z cieniem tekstu

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
        $el = $(el);
        text = $el.text();
        chars = text.split('');

        // Set the screen-reader text
        $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

        // Reset output for appending
        output = '';

        // Iterate over all chars in the text
        for (i = 0; i < chars.length; i++) {
            // Create a styled element for each character and append to container
            output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
        }

        // Write to DOM only once
        $el.append(output);
    });
});
.halfStyle {
  position: relative;
  display: inline-block;
  font-size: 80px; /* or any font size will work */
  color: transparent; /* hide the base character */
  overflow: hidden;
  white-space: pre; /* to preserve the spaces from collapsing */
}

.halfStyle:before { /* creates the top part */
  display: block;
  z-index: 2;
  position: absolute;
  top: 0;
  height: 50%;
  content: attr(data-content); /* dynamic content for the pseudo element */
  overflow: hidden;
  pointer-events: none; /* so the base char is selectable by mouse */
  color: #f00; /* for demo purposes */
  text-shadow: 2px -2px 0px #af0; /* for demo purposes */
}

.halfStyle:after { /* creates the bottom part */
  display: block;
  position: absolute;
  z-index: 1;
  top: 0;
  height: 100%;
  content: attr(data-content); /* dynamic content for the pseudo element */
  overflow: hidden;
  pointer-events: none; /* so the base char is selectable by mouse */
  color: #000; /* for demo purposes */
  text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

(JSFiddle demo)



- Pionowe 1/3 Części

  • Bez Cienia Tekstu:

    halfStyle-pionowa 1/3 części - bez cienia tekstu

  • Możliwość cienia tekstu dla każdej 1/3 części niezależnie:

    halfStyle-pionowa 1/3 części - z cieniem tekstu

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
.halfStyle { /* base char and also the right 1/3 */
    position: relative;
    display: inline-block;
    font-size: 80px; /* or any font size will work */
    color: transparent; /* hide the base character */
    overflow: hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
    color: #f0f; /* for demo purposes */
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}

.halfStyle:before { /* creates the left 1/3 */
    display: block;
    z-index: 2;
    position: absolute;
    top: 0;
    width: 33.33%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #f00; /* for demo purposes */
    text-shadow: 2px -2px 0px #af0; /* for demo purposes */
}

.halfStyle:after { /* creates the middle 1/3 */
    display: block;
    z-index: 1;
    position: absolute;
    top: 0;
    width: 66.66%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #000; /* for demo purposes */
    text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

(jsfiddle demo )



- Poziome 1/3 Części

  • Bez Tekstu Cień:

    halfStyle-poziome 1/3 części - bez cienia tekstu

  • Możliwość cienia tekstu dla każdej 1/3 części niezależnie:

    halfStyle-pozioma 1/3 części - z cieniem tekstu

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
.halfStyle { /* base char and also the bottom 1/3 */
  position: relative;
  display: inline-block;
  font-size: 80px; /* or any font size will work */
  color: transparent;
  overflow: hidden;
  white-space: pre; /* to preserve the spaces from collapsing */
  color: #f0f;
  text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}

.halfStyle:before { /* creates the top 1/3 */
  display: block;
  z-index: 2;
  position: absolute;
  top: 0;
  height: 33.33%;
  content: attr(data-content); /* dynamic content for the pseudo element */
  overflow: hidden;
  pointer-events: none; /* so the base char is selectable by mouse */
  color: #f00; /* for demo purposes */
  text-shadow: 2px -2px 0px #fa0; /* for demo purposes */
}

.halfStyle:after { /* creates the middle 1/3 */
  display: block;
  position: absolute;
  z-index: 1;
  top: 0;
  height: 66.66%;
  content: attr(data-content); /* dynamic content for the pseudo element */
  overflow: hidden;
  pointer-events: none; /* so the base char is selectable by mouse */
  color: #000; /* for demo purposes */
  text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

(jsfiddle demo )



- HalfStyle Improvement By @ KevinGranger

halfStyle-KevinGranger

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
body {
    background-color: black;
}

.textToHalfStyle {
    display: block;
    margin: 200px 0 0 0;
    text-align: center;
}

.halfStyle {
    font-family: 'Libre Baskerville', serif;
    position: relative;
    display: inline-block;
    width: 1;
    font-size: 70px;
    color: black;
    overflow: hidden;
    white-space: pre;
    text-shadow: 1px 2px 0 white;
}

.halfStyle:before {
    display: block;
    z-index: 1;
    position: absolute;
    top: 0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

(jsfiddle demo )



- PeelingStyle poprawa HalfStyle przez @SamTremaine

halfStyle-SamTremaine

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
.halfStyle {
    position: relative;
    display: inline-block;
    font-size: 68px;
    color: rgba(0, 0, 0, 0.8);
    overflow: hidden;
    white-space: pre;
    transform: rotate(4deg);
    text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);
}

.halfStyle:before { /* creates the left part */
    display: block;
    z-index: 1;
    position: absolute;
    top: -0.5px;
    left: -3px;
    width: 100%;
    content: attr(data-content);
    overflow: hidden;
    pointer-events: none;
    color: #FFF;
    transform: rotate(-4deg);
    text-shadow: 0px 0px 1px #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

(jsfiddle demo i na samtremaine.co.uk )



Część 4: gotowe do produkcji

Dostosowane różne zestawy stylów mogą być używane na pożądanych elementach na tej samej stronie. Możesz zdefiniować wiele zestawów stylów i powiedzieć wtyczce, którego z nich użyć.

Plugin używa atrybutu data data-halfstyle="[-CustomClassName-]" na celu .textToHalfStyle elementów i dokonuje wszystkich niezbędnych zmian automatycznie.

Więc po prostu na elemencie zawierającym tekst dodaj textToHalfStyle klasę i atrybut danych data-halfstyle="[-CustomClassName-]". Wtyczka wykona resztę pracy.

halfStyle-wiele na tej samej stronie

Również definicje klas CSS style-sets pasują do [-CustomClassName-] części wymienionej powyżej i są przykute do .halfStyle, więc będziemy mieli .halfStyle.[-CustomClassName-]

jQuery(function($) {
    var halfstyle_text, halfstyle_chars, $halfstyle_el, halfstyle_i, halfstyle_output, halfstyle_style;

    // Iterate over all class occurrences
    $('.textToHalfStyle').each(function(idx, halfstyle_el) {
        $halfstyle_el = $(halfstyle_el);
        halfstyle_style = $halfstyle_el.data('halfstyle') || 'hs-base';
        halfstyle_text = $halfstyle_el.text();
        halfstyle_chars = halfstyle_text.split('');

        // Set the screen-reader text
        $halfstyle_el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + halfstyle_text + '</span>');

        // Reset output for appending
        halfstyle_output = '';

        // Iterate over all chars in the text
        for (halfstyle_i = 0; halfstyle_i < halfstyle_chars.length; halfstyle_i++) {
            // Create a styled element for each character and append to container
            halfstyle_output += '<span aria-hidden="true" class="halfStyle ' + halfstyle_style + '" data-content="' + halfstyle_chars[halfstyle_i] + '">' + halfstyle_chars[halfstyle_i] + '</span>';
        }

        // Write to DOM only once
        $halfstyle_el.append(halfstyle_output);
    });
});
/* start half-style hs-base */

.halfStyle.hs-base {
    position: relative;
    display: inline-block;
    font-size: 80px; /* or any font size will work */
    overflow: hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
    color: #000; /* for demo purposes */
}

.halfStyle.hs-base:before {
    display: block;
    z-index: 1;
    position: absolute;
    top: 0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    pointer-events: none; /* so the base char is selectable by mouse */
    overflow: hidden;
    color: #f00; /* for demo purposes */
}

/* end half-style hs-base */


/* start half-style hs-horizontal-third */

.halfStyle.hs-horizontal-third { /* base char and also the bottom 1/3 */
    position: relative;
    display: inline-block;
    font-size: 80px; /* or any font size will work */
    color: transparent;
    overflow: hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
    color: #f0f;
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}

.halfStyle.hs-horizontal-third:before { /* creates the top 1/3 */
    display: block;
    z-index: 2;
    position: absolute;
    top: 0;
    height: 33.33%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #f00; /* for demo purposes */
    text-shadow: 2px -2px 0px #fa0; /* for demo purposes */
}

.halfStyle.hs-horizontal-third:after { /* creates the middle 1/3 */
    display: block;
    position: absolute;
    z-index: 1;
    top: 0;
    height: 66.66%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #000; /* for demo purposes */
    text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}

/* end half-style hs-horizontal-third */


/* start half-style hs-PeelingStyle, by user SamTremaine on Stackoverflow.com */

.halfStyle.hs-PeelingStyle {
  position: relative;
  display: inline-block;
  font-size: 68px;
  color: rgba(0, 0, 0, 0.8);
  overflow: hidden;
  white-space: pre;
  transform: rotate(4deg);
  text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);
}

.halfStyle.hs-PeelingStyle:before { /* creates the left part */
  display: block;
  z-index: 1;
  position: absolute;
  top: -0.5px;
  left: -3px;
  width: 100%;
  content: attr(data-content);
  overflow: hidden;
  pointer-events: none;
  color: #FFF;
  transform: rotate(-4deg);
  text-shadow: 0px 0px 1px #000;
}

/* end half-style hs-PeelingStyle */


/* start half-style hs-KevinGranger, by user KevinGranger on StackOverflow.com*/

.textToHalfStyle.hs-KevinGranger {
  display: block;
  margin: 200px 0 0 0;
  text-align: center;
}

.halfStyle.hs-KevinGranger {
  font-family: 'Libre Baskerville', serif;
  position: relative;
  display: inline-block;
  width: 1;
  font-size: 70px;
  color: black;
  overflow: hidden;
  white-space: pre;
  text-shadow: 1px 2px 0 white;
}

.halfStyle.hs-KevinGranger:before {
  display: block;
  z-index: 1;
  position: absolute;
  top: 0;
  width: 50%;
  content: attr(data-content); /* dynamic content for the pseudo element */
  overflow: hidden;
  color: white;
}

/* end half-style hs-KevinGranger
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
    <span class="textToHalfStyle" data-halfstyle="hs-base">Half-style, please.</span>
</p>
<p>
    <span class="textToHalfStyle" data-halfstyle="hs-horizontal-third">Half-style, please.</span>
</p>
<p>
    <span class="textToHalfStyle" data-halfstyle="hs-PeelingStyle">Half-style, please.</span>
</p>
<p style="background-color:#000;">
    <span class="textToHalfStyle" data-halfstyle="hs-KevinGranger">Half-style, please.</span>
</p>

(jsfiddle demo )

 2686
Author: Arbel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-29 07:30:42

Tutaj wpisz opis obrazka


Właśnie skończyłem opracowywać wtyczkę i jest ona dostępna dla każdego! Mam nadzieję, że ci się spodoba.

Zobacz projekt na GitHub - zobacz projekt Strona internetowa. (więc możesz zobaczyć wszystkie style podziału)

użycie

Przede wszystkim upewnij się, że biblioteka jQuery jest dołączona. Najlepszym sposobem na uzyskanie najnowszej wersji jQuery jest zaktualizowanie tagu head o:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

Po pobierając pliki, upewnij się, że włączyłeś je do swojego projektu:

<link rel="stylesheet" type="text/css" href="css/splitchar.css">
<script type="text/javascript" src="js/splitchar.js"></script>

znaczniki

Wszystko, co musisz zrobić, to dołączyć klasę splitchar, a następnie żądany styl do elementu zawijającego Twój tekst. e. g

<h1 class="splitchar horizontal">Splitchar</h1>

Po tym wszystkim, upewnij się, że wywołujesz funkcję jQuery w pliku gotowym do dokumentu w następujący sposób:

$(".splitchar").splitchar();

dostosowywanie

Aby tekst wyglądał dokładnie tak, jak chcesz, wystarczy, że zastosuj swój projekt w następujący sposób:

.horizontal { /* Base CSS - e.g font-size */ }
.horizontal:before { /* CSS for the left half */ }
.horizontal:after { /* CSS for the right half */ }


To jest to! Teraz masz wtyczkę Splitchar ustawioną. Więcej informacji na ten temat na http://razvanbalosin.com/Splitchar.js/.

 459
Author: Razvan Balosin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-25 17:20:15

Edit (październik 2017): background-clip a raczej background-image options są teraz obsługiwane przez wszystkie główne przeglądarki: CanIUse

Tak, możesz to zrobić tylko jednym znakiem i tylko CSS.

Tylko Webkit (i Chrome), chociaż:

Http://jsbin.com/rexoyice/1/

h1 {
  display: inline-block;
  margin: 0; /* for demo snippet */
  line-height: 1em; /* for demo snippet */
  font-family: helvetica, arial, sans-serif;
  font-weight: bold;
  font-size: 300px;
  background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
<h1>X</h1>

Wizualnie wszystkie przykłady, które używają dwóch znaków (czy to przez js, pseudo elementy CSS, czy po prostu HTML), wyglądają dobrze, ale zauważ, że wszystkie dodają treść do DOM, co może powodować problemy z dostępnością--jak również z zaznaczeniem/wycinaniem/wklejaniem tekstu.

 203
Author: DA.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-13 10:28:27

Przykład


JSFIDDLE DEMO

Zrobimy to używając tylko pseudo selektorów CSS!

Ta technika będzie działać z dynamicznie generowaną treścią i różnymi rozmiarami i szerokościami czcionek.

HTML:

<div class='split-color'>Two is better than one.</div>

CSS:

.split-color > span {
    white-space: pre-line;
    position: relative;
    color: #409FBF;
}

.split-color > span:before {
    content: attr(data-content);
    pointer-events: none;  /* Prevents events from targeting pseudo-element */
    position: absolute;
    overflow: hidden;
    color: #264A73;
    width: 50%;
    z-index: 1;
}

Aby zawinąć dynamicznie generowany ciąg znaków, możesz użyć funkcji takiej jak Ta:

// Wrap each letter in a span tag and return an HTML string
// that can be used to replace the original text
function wrapString(str) {
  var output = [];
  str.split('').forEach(function(letter) {
    var wrapper = document.createElement('span');
    wrapper.dataset.content = wrapper.innerHTML = letter;

    output.push(wrapper.outerHTML);
  });

  return output.join('');
}

// Replace the original text with the split-color text
window.onload = function() {
    var el  = document.querySelector('.split-color'),
        txt = el.innerHTML;

    el.innerHTML = wrapString(txt);
}
 141
Author: wvandaal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-11 19:54:54

To może być nieistotne, może nie, ale jakiś czas temu stworzyłem funkcję jQuery, która robi to samo, ale poziomo.

Nazwałem go "Strippex" dla 'stripe' + 'text', demo: http://cdpn.io/FcIBg

Nie mówię, że jest to rozwiązanie wszelkich problemów, ale już próbowałem zastosować css do połowy znaku, ale poziomo, więc pomysł jest ten sam, realizacja może być okropna, ale działa.

Ah, i najważniejsze, bawiłem się tworząc to !

Tutaj wpisz opis obrazka

 88
Author: LukyVj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-15 21:58:27

Tutaj brzydka implementacja w canvasie. Próbowałem tego rozwiązania, ale wyniki są gorsze niż się spodziewałem, więc i tak oto jest.

Przykład płótna

        $("div").each(function(){
            var CHARS = $(this).text().split('');
            $(this).html("");
            $.each(CHARS,function(index, char){
                var canvas = $("<canvas />")
                        .css("width", "40px")
                        .css("height", "40px")
                        .get(0);
                $("div").append(canvas);
                var ctx = canvas.getContext("2d");
                var gradient = ctx.createLinearGradient(0, 0, 130, 0);
                gradient.addColorStop("0", "blue");
                gradient.addColorStop("0.5", "blue");
                gradient.addColorStop("0.51", "red");
                gradient.addColorStop("1.0", "red");
                ctx.font = '130pt Calibri';
                ctx.fillStyle = gradient;
                ctx.fillText(char, 10, 130);
            });
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Example Text</div>
 64
Author: HaSuKrOnOs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-21 14:46:58

Jeśli jesteś tym zainteresowany, to usterka Lucasa Bebbera jest bardzo podobnym i super fajnym efektem:

Tutaj wpisz opis obrazka

Stworzony przy użyciu prostego mixu SASSOWEGO, takiego jak

.example-one {
  font-size: 100px;
  @include textGlitch("example-one", 17, white, black, red, blue, 450, 115);
}

Więcej szczegółów na Chris Coyer 's CSS Tricksi Lucas Bebber' s Codepen page

 62
Author: Ruskin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-01 12:39:25

Najbliżej mogę dostać:

$(function(){
  $('span').width($('span').width()/2);
  $('span:nth-child(2)').css('text-indent', -$('span').width());
});
body{
  font-family: arial;
}
span{
  display: inline-block;
  overflow: hidden;
}
span:nth-child(2){
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>X</span><span>X</span>

Demo: http://jsfiddle.net/9wxfY/2/

Heres a version that just uses one span: http://jsfiddle.net/9wxfY/4/

 54
Author: Prisoner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-05 11:46:26

Tutaj wpisz opis obrazka

Właśnie pobawiłem się rozwiązaniem @Arbel:

var textToHalfStyle = $('.textToHalfStyle').text();
var textToHalfStyleChars = textToHalfStyle.split('');
$('.textToHalfStyle').html('');
$.each(textToHalfStyleChars, function(i,v){
    $('.textToHalfStyle').append('<span class="halfStyle" data-content="' + v + '">' + v + '</span>');
});
body{
    background-color: black;
}
.textToHalfStyle{
    display:block;
    margin: 200px 0 0 0;
    text-align:center;
}
.halfStyle {
    font-family: 'Libre Baskerville', serif;
    position:relative;
    display:inline-block;
    width:1;
    font-size:70px;
    color: black;
    overflow:hidden;
    white-space: pre;
    text-shadow: 1px 2px 0 white;
}
.halfStyle:before {
    display:block;
    z-index:1;
    position:absolute;
    top:0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow:hidden;
    color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<span class="textToHalfStyle">Dr. Jekyll and M. Hide</span>
 50
Author: Shipow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-21 17:39:34

Inne rozwiązanie tylko dla CSS (chociaż atrybut data jest potrzebny, jeśli nie chcesz pisać CSS specyficznego dla liter). Ten działa bardziej ogólnie (testowane IE 9/10, Chrome latest & FF latest)

span {
  position: relative;
  color: rgba(50,50,200,0.5);
}

span:before {
  content: attr(data-char);
  position: absolute;
  width: 50%;
  overflow: hidden;
  color: rgb(50,50,200);
}
<span data-char="X">X</span>
 41
Author: MStrutt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-05 12:40:24

Ograniczone rozwiązanie CSS i jQuery

Nie jestem pewien, jak eleganckie jest to rozwiązanie, ale tnie wszystko dokładnie na pół: http://jsfiddle.net/9wxfY/11/

W przeciwnym razie, stworzyłem dla ciebie dobre rozwiązanie... Wszystko, co musisz zrobić, to mieć to dla swojego HTML:

Zobacz najnowszą i dokładną edycję z 13/06/2016: http://jsfiddle.net/9wxfY/43/

Jeśli chodzi o CSS, jest on bardzo ograniczony... Tylko Ty trzeba go zastosować do :nth-child(even)

$(function(){
  var $hc = $('.half-color');
  var str = $hc.text();
  $hc.html("");

  var i = 0;
  var chars;
  var dupText;

  while(i < str.length){
    chars = str[i];
    if(chars == " ") chars = "&nbsp;";
    dupText = "<span>" + chars + "</span>";

    var firstHalf = $(dupText);
    var secondHalf = $(dupText);

    $hc.append(firstHalf)
    $hc.append(secondHalf)

    var width = firstHalf.width()/2;

    firstHalf.width(width);
    secondHalf.css('text-indent', -width);

    i++;
  }
});
.half-color span{
  font-size: 2em;
  display: inline-block;
  overflow: hidden;
}
.half-color span:nth-child(even){
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="half-color">This is a sentence</div>
 35
Author: Adjit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-19 15:23:22
.halfStyle {
    position:relative;
    display:inline-block;
    font-size:68px; /* or any font size will work */
    color: rgba(0,0,0,0.8); /* or transparent, any color */
    overflow:hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
    transform:rotate(4deg);
    -webkit-transform:rotate(4deg);
    text-shadow:2px 1px 3px rgba(0,0,0,0.3);
}
.halfStyle:before {
    display:block;
    z-index:1;
    position:absolute;
    top:-0.5px;
    left:-3px;
    width: 100%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow:hidden;
    color: white;
    transform:rotate(-4deg);
    -webkit-transform:rotate(-4deg);
    text-shadow:0 0 1px black;

}

Http://experimental.samtremaine.co.uk/half-style/

Możesz zmusić ten kod do robienia różnego rodzaju ciekawych rzeczy - to tylko jedna implementacja, którą wymyśliłem wczoraj z moim współpracownikiem.

 28
Author: Sam Tremaine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-13 09:26:24

Ładne rozwiązanie tylko dla WebKit, które wykorzystuje wsparcie background-clip: text: http://jsfiddle.net/sandro_paganotti/wLkVt/

span{
   font-size: 100px;
   background: linear-gradient(to right, black, black 50%, grey 50%, grey);
   -webkit-background-clip: text;
   -webkit-text-fill-color: transparent;
}
 23
Author: Sandro Paganotti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-09 17:50:04

FWIW, oto moje zdanie na ten temat robiąc to tylko z CSS: http://codepen.io/ricardozea/pen/uFbts/

Kilka uwag:

  • Głównym powodem, dla którego to zrobiłem, było przetestowanie siebie i sprawdzenie, czy udało mi się osiągnąć stylizację połowy postaci, jednocześnie zapewniając sensowną odpowiedź na OP.

  • Zdaję sobie sprawę, że nie jest to rozwiązanie idealne lub najbardziej skalowalne, a rozwiązania proponowane przez ludzi tutaj są o wiele lepsze dla " realnego świata" scenariusze.

  • Kod CSS, który stworzyłem, opiera się na pierwszych myślach, które przyszły mi do głowy i moim osobistym podejściu do problemu.

  • Moje rozwiązanie działa tylko na znakach symetrycznych, takich jak X, A, O, M. * * nie działa na znakach asymetrycznych, takich jak B, C, F, K lub małe litery.

  • ** jednak takie podejście tworzy bardzo ciekawe "kształty" z asymetrycznymi znakami. Spróbuj zmienić X Na K lub na małą literę, jak na h lub a p W CSS :)

HTML

<span class="half-letter"></span>

SCSS

.half-character { 
  display: inline-block;
  font: bold 350px/.8 Arial;
  position: relative;

  &:before, &:after {
    content: 'X'; //Change character here
    display: inline-block;
    width: 50%;
    overflow: hidden;
    color: #7db9e8;
  }
  &:after {
    position: absolute;
    top: 0;
    left: 50%;
    color: #1e5799;
    transform: rotateY(-180deg);
  }
}
 21
Author: Ricardo Zea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-31 19:19:13

Możesz to również zrobić używając SVG, jeśli chcesz:

var title = document.querySelector('h1'),
    text = title.innerHTML,
    svgTemplate = document.querySelector('svg'),
    charStyle = svgTemplate.querySelector('#text');

svgTemplate.style.display = 'block';

var space = 0;

for (var i = 0; i < text.length; i++) {
  var x = charStyle.cloneNode();
  x.textContent = text[i];
  svgTemplate.appendChild(x);
  x.setAttribute('x', space);
  space += x.clientWidth || 15;
}

title.innerHTML = '';
title.appendChild(svgTemplate);
<svg style="display: none; height: 100px; width: 100%" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
    <defs id="FooDefs">
        <linearGradient id="MyGradient" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="50%" stop-color="blue" />
            <stop offset="50%" stop-color="red" />
        </linearGradient>
    </defs>
    <text y="50%" id="text" style="font-size: 72px; fill: url(#MyGradient)"></text>
</svg>

<h1>This is not a solution X</h1>

Http://codepen.io/nicbell/pen/jGcbq

 15
Author: Nic Bell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-06 10:43:30

Może coś takiego dla krótszego tekstu?

Może nawet działać dla dłuższego tekstu, jeśli zrobisz coś z pętlą, powtarzając znaki z JavaScript. W każdym razie wynik jest coś takiego:

Czy można zastosować CSS do połowy znaku?

p.char {
  position: relative;
  display: inline-block;
  font-size: 60px;
  color: red;
}

p.char:before {
  position: absolute;
  content: attr(char);
  width: 50%;
  overflow: hidden;
  color: black;
}
<p class="char" char="S">S</p>
<p class="char" char="t">t</p>
<p class="char" char="a">a</p>
<p class="char" char="c">c</p>
<p class="char" char="k">k</p>
<p class="char" char="o">o</p>
<p class="char" char="v">v</p>
<p class="char" char="e">e</p>
<p class="char" char="r">r</p>
<p class="char" char="f">f</p>
<p class="char" char="l">l</p>
<p class="char" char="o">o</p>
<p class="char" char="w">w</p>
 15
Author: Alireza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-11 06:22:25

Można to osiągnąć za pomocą selektora CSS :before i content property value.

.halfed, .halfed1 {
  float: left;
}

.halfed, .halfed1 {
  font-family: arial;
  font-size: 300px;
  font-weight: bolder;
  width: 200px;
  height: 300px;
  position: relative; /* To help hold the content value within */
  overflow: hidden;
  color: #000;
}




.halfed:before, .halfed1:before   {
  width: 50%; /* How much we'd like to show */
  overflow: hidden; /* Hide what goes beyond our dimension */  
  content: 'X'; /* Halfed character */
  height: 100%;
  position: absolute;
  color: #28507D;

}



/* For Horizontal cut off */ 

.halfed1:before   {
  width: 100%;
  height: 55%;
  
}
<div class="halfed"> X </div>

<div class="halfed1"> X </div>

>> Zobacz na jsFiddle

 14
Author: Sleek Geek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-14 14:50:56

Możesz użyć poniższego kodu. W tym przykładzie użyłem znacznika h1 i dodałem atrybut data-title-text="Display Text", który będzie wyświetlał się z innym kolorowym tekstem na elemencie tekstowym znacznika h1, co daje efekt półkolorowanego tekstu, jak pokazano w poniższym przykładzie

Tutaj wpisz opis obrazka

body {
  text-align: center;
  margin: 0;
}

h1 {
  color: #111;
  font-family: arial;
  position: relative;
  font-family: 'Oswald', sans-serif;
  display: inline-block;
  font-size: 2.5em;
}

h1::after {
  content: attr(data-title-text);
  color: #e5554e;
  position: absolute;
  left: 0;
  top: 0;
  clip: rect(0, 1000px, 30px, 0);
}
<h1 data-title-text="Display Text">Display Text</h1>
 7
Author: GSB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-11 07:12:16