내가 찾고있는 것 :
한 문자의HALF스타일을 지정하는 방법. (이 경우 문자의 절반은 투명합니다.)
내가 현재 검색하고 시도한 것 (행운이 없음) :
아래는 내가 얻으려고하는 것의 예입니다.
이를 위해 CSS 또는 JavaScript 솔루션이 존재합니까, 아니면 이미지를 사용해야할까요? 이 텍스트가 동적으로 생성되기 때문에 이미지 경로를 가지 않는 것이 좋습니다.
업데이트 :
왜 내가 캐릭터의 절반을 왜 스타일링하고 싶은지 많은 사람들이 물었 기 때문에 이것이 이유입니다. 우리시는 최근에 새로운 "브랜드"를 정의하기 위해 25 만 달러를 사용했습니다. 이logo그들이 생각해 낸 것입니다. 많은 사람들이 단순함과 창의력 부족에 대해 불평하고 계속 그렇게합니다. 나의 목표는이웹 사이트를 농담으로 생각해내는 것이 었습니다. 'Halifax'를 입력하면 내 뜻을 알 수 있습니다.
기분 전환하고 개선하십시오.
데모 :http://jsfiddle.net/arbel/pd9yB/1694/
이것은 모든 동적 텍스트 또는 단일 문자에서 작동하며 모두 자동화됩니다. 타겟 텍스트에 클래스를 추가하고 나머지는 처리합니다.
또한 원문의 접근성은 시각 장애인이나 시각 장애인을위한 스크린 리더를 위해 보존됩니다.
단일 문자 설명 :
순수한 CSS. 스타일을 지정하려는 캐릭터가 포함 된 각 요소에 .halfStyle
클래스를 적용하면됩니다.
문자가 포함 된 각 span 요소에 대해 예를 들어 여기 data-content="X"
와 같은 데이터 속성을 만들 수 있고 의사 요소에서 content: attr(data-content);
을 사용하면 .halfStyle:before
클래스가 동적이되고 모든 인스턴스에 대해 하드 코드 할 필요가 없습니다.
텍스트 설명 :
텍스트를 포함하는 요소에 textToHalfStyle
class를 추가하기 만하면됩니다.
// 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 데모 )
이 솔루션을 사용하면 왼쪽 및 오른쪽 부분을 개별적으로 또는 독립적으로 스타일링 할 수 있음.
모든 것이 동일하고 더 진보 된 CSS만이 마술을합니다.
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 데모 )
이제는 무엇이 가능한지 알았으므로 몇 가지 변형을 만들어 보겠습니다.
// 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 데모 )
// 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 데모 )
// 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 데모 )
// 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 데모 )
// 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 데모 와 samtremaine.co.uk )
사용자 정의 된 다른 Half-Style 스타일 세트는 동일한 페이지의 원하는 요소에 사용할 수 있습니다. 여러 스타일 세트를 정의하고 사용할 스타일을 플러그인에 알릴 수 있습니다.
플러그인은 대상 data-halfstyle="[-CustomClassName-]"
요소에서 데이터 속성 .textToHalfStyle
를 사용하고 필요한 모든 변경을 자동으로 수행합니다.
따라서 텍스트를 포함하는 요소에 textToHalfStyle
클래스와 데이터 속성 data-halfstyle="[-CustomClassName-]"
를 추가하면됩니다. 플러그인이 나머지 작업을 수행합니다.
또한 CSS 스타일 세트의 클래스 정의는 위에서 언급 한 [-CustomClassName-]
부분과 일치하고 .halfStyle
에 체인되어 있으므로 .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 데모 )
플러그인 개발을 마쳤으며 모두가 사용할 수 있습니다! 희망 당신은 그것을 즐길 수 있습니다.
우선, jQuery
라이브러리가 포함되어 있는지 확인하십시오. 최신 jQuery 버전을 얻는 가장 좋은 방법은 head 태그를 다음과 같이 업데이트하는 것입니다.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
파일을 다운로드 한 후 프로젝트에 파일을 포함했는지 확인하십시오.
<link rel="stylesheet" type="text/css" href="css/splitchar.css">
<script type="text/javascript" src="js/splitchar.js"></script>
splitchar
클래스를 asign하기 만하면 텍스트를 감싸는 요소에 원하는 스타일이 뒤따라야합니다. 예 :
<h1 class="splitchar horizontal">Splitchar</h1>
이 모든 작업이 끝나면 다음과 같이 문서 준비 파일에서 jQuery 함수를 호출해야합니다.
$(".splitchar").splitchar();
텍스트를 원하는대로 정확하게 보이게하려면 다음과 같이 디자인을 적용하면됩니다.
.horizontal { /* Base CSS - e.g font-size */ }
.horizontal:before { /* CSS for the left half */ }
.horizontal:after { /* CSS for the right half */ }
그게 다야! 이제 Splitchar
플러그인이 모두 설정되었습니다. 그것에 대한 자세한 정보는 http://razvanbalosin.com/Splitchar.js/ .
Edit (oct 2017) : 모든 주요 브라우저에서
background-clip
또는background-image options
가 지원됩니다. CanIUse
그렇습니다. 단 하나의 캐릭터와 CSS만으로이 작업을 수행 할 수 있습니다.
웹킷 (및 크롬) :
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>
시각적으로 두 문자를 사용하는 모든 예제 (JS, CSS 유사 요소 또는 HTML 만 가능)는 모두 멋지지만 모든 요소가 DOM에 콘텐츠를 추가하여 액세스 가능성을 유발할 수 있으며 텍스트 선택/잘라 내기/붙여 넣기 문제.
우리는 단지 CSS 의사 선택기를 사용하여 그것을 할 것입니다!
이 기술은 동적으로 생성 된 내용과 다양한 글꼴 크기 및 너비에서 작동합니다.
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;
}
동적으로 생성 된 문자열을 래핑하려면 다음과 같은 함수를 사용할 수 있습니다.
// 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);
}
관련이 없거나 아닐 수도 있지만 언젠가는 같은 일을하지만 수평 적으로 jQuery 함수를 만들었습니다.
나는 그것을 "Strippex"라고 불렀다. 'stripe'+ 'text', 데모 : http://cdpn.io/FcIBg
나는 이것이 어떤 문제의 해결책이라고 말하는 것이 아니라, 이미 캐릭터의 절반에 CSS를 적용하려고 시도했지만, 수평 적으로, 아이디어는 동일하다. 실현은 끔찍할 수 있지만 작동한다.
아, 그리고 가장 중요한 것은, 나는 그것을 만드는 재미를 보았습니다!
여기 캔버스에 못생긴 구현. 이 솔루션을 시도했지만 결과가 예상보다 나빴습니다. 어쨌든 여기에 있습니다.
$("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>
이것에 관심이 있다면 Lucas Bebber의 Glitch는 매우 유사하고 멋진 효과입니다.
다음과 같은 간단한 SASS Mixin을 사용하여 생성
.example-one {
font-size: 100px;
@include textGlitch("example-one", 17, white, black, red, blue, 450, 115);
}
Chris Coyer의 CSS 트릭 및 Lucas Bebber의 Codepen 페이지 에서 자세한 내용
가장 가까운 곳 :
$(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>
데모 : http://jsfiddle.net/9wxfY/2/
한 스팬 만 사용하는 버전이 있습니다 : http://jsfiddle.net/9wxfY/4/
방금 @ 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>
또 다른 CSS 전용 솔루션 (문자 별 CSS 작성을 원하지 않으면 데이터 속성이 필요합니다). 이 기능은 전반적으로 작동합니다 (Tested 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>
제한된 CSS 및 jQuery 솔루션
이 솔루션이 얼마나 우아 할 지 모르겠지만 모든 것을 정확히 반으로 자릅니다. http://jsfiddle.net/9wxfY/11/
그렇지 않으면, 당신을 위해 멋진 솔루션을 만들었습니다 ... 당신이해야 할 일은 HTML을위한 것입니다 :
2014 년 6 월 13 일 기준으로 가장 최근의 정확한 내용을 살펴보십시오. http://jsfiddle.net/9wxfY/43/
CSS에 관해서는 매우 제한적입니다 ... :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 = " ";
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>
.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/
이 코드를 사용하면 모든 종류의 흥미로운 작업을 수행 할 수 있습니다.이 작업은 동료와 내가 지난 밤에 생각해 낸 것 중 하나입니다.
background-clip: text
지원을 활용하는 멋진 WebKit 전용 솔루션 : 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;
}
FWIW, 여기 CSS로만이 작업을 수행합니다. http://codepen.io/ricardozea/pen/uFbts/
몇 가지 메모 :
내가 이것을 한 주된 이유는 나 자신을 시험하고 OP의 의미있는 대답을 실제로 제공하면서 캐릭터의 절반을 스타일링 할 수 있는지를 확인하는 것이 었습니다.
나는 이것이 이상적이거나 가장 확장 성있는 해결책이 아니며 여기서 사람들이 제안한 해결책이 "현실 세계"시나리오보다 훨씬 우수하다는 것을 알고 있습니다.
내가 작성한 CSS 코드는 내 마음에 나온 첫 번째 생각과 문제에 대한 내 개인적인 접근 방식을 기반으로합니다.
내 솔루션은 X, A, O, M과 같은 대칭 문자에서만 작동합니다. ** B, C, F, K 또는 소문자와 같은 비대칭 문자에서는 작동하지 않습니다.
** 그러나,이 접근법은 비대칭 문자로 매우 흥미로운 '모양'을 만듭니다. X를 K 또는 h 또는 p와 같은 소문자로 변경하십시오.
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);
}
}
더 짧은 텍스트를 위해 이런 식으로 어떻습니까?
반복문을 사용하여 JavaScript로 문자를 반복하면 텍스트가 길어질 수도 있습니다. 어쨌든 결과는 다음과 같습니다.
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>
원하는 경우 SVG를 사용하여 다음 작업을 수행 할 수도 있습니다.
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>
이것은 CSS :before
셀렉터와 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>
아래 코드를 사용할 수 있습니다. 여기이 예제에서는 h1
태그를 사용하고 data-title-text="Display Text"
속성을 추가했습니다.이 속성은 h1
태그 텍스트 요소에 다른 색상의 텍스트와 함께 표시되며, 아래 예제와 같이 반쪽 텍스트가 적용됩니다
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>
역사상의 기록을 위해서!
나는 5-6 년 전부터 Gradext (순수한 자바 스크립트와 순수한 CSS, 의존성이 없음)에서 내 자신의 작업을위한 해결책을 찾았다.
기술적 인 설명은 다음과 같은 요소를 생성 할 수 있다는 것입니다.
<span>A</span>
이제 텍스트에 그라디언트를 만들려면 여러 개의 레이어를 만들 필요가 있습니다. 각각의 레이어는 개별적으로 색이 지정되고 만들어지는 스펙트럼은 그라디언트 효과를 보여줍니다.
예를 들어, 이것은 <span>
내부에있는 단어 lorem을 (를) 볼 수 있으며 ( 예제를 확인하십시오 ) :
<span data-i="0" style="color: rgb(153, 51, 34);">L</span>
<span data-i="1" style="color: rgb(154, 52, 35);">o</span>
<span data-i="2" style="color: rgb(155, 53, 36);">r</span>
<span data-i="3" style="color: rgb(156, 55, 38);">e</span>
<span data-i="4" style="color: rgb(157, 56, 39);">m</span>
그리고 오랫동안 긴 단락에도이 패턴을 계속할 수 있습니다.
세로 그라디언트텍스트에 대한 효과?
그런 다음 도움이 될 수있는 또 다른 해결책이 있습니다. 나는 세부적으로 설명 할 것이다.
우리의 첫 번째 <span>
가정합니다. 내용은 개별적으로 글자가되어서는 안됩니다. 내용은 전체 텍스트 여야하며 이제는 동일한 <span>
를 반복해서 복사합니다 (스팬 수는 그라디언트의 품질, 더 긴 기간, 더 나은 결과를 나타내지 만 성능은 좋지 않음을 정의합니다). 이것 좀 봐 :
<span data-i="6" style="color: rgb(81, 165, 39); overflow: hidden; height: 11.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="7" style="color: rgb(89, 174, 48); overflow: hidden; height: 12.8px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="8" style="color: rgb(97, 183, 58); overflow: hidden; height: 14.4px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="9" style="color: rgb(105, 192, 68); overflow: hidden; height: 16px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="10" style="color: rgb(113, 201, 78); overflow: hidden; height: 17.6px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="11" style="color: rgb(121, 210, 88); overflow: hidden; height: 19.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
이러한 그라디언트 효과를 이동하여 애니메이션으로 만들려면 어떻게해야할까요?
음, 또 다른 해결책이 있습니다. 커서 위치를 기준으로 그라디언트가 시작되도록 animation: true
또는 .hoverable()
메소드를 반드시 확인해야합니다! (차가운 xD 소리)
이것은 단순히 텍스트에 그라디언트 (선형 또는 방사형)를 만드는 방법입니다. 아이디어가 마음에 들었거나 그것에 대해 더 알고 싶다면 제공된 링크를 확인해야합니다.
어쩌면이 방법이 최선의 선택이 아니며 가장 좋은 방법은 아닐 수도 있지만 더 나은 솔루션을 위해 다른 사람들에게 영감을 불어 넣을 흥미롭고 즐거운 애니메이션을 만들기위한 공간을 열어 놓을 것입니다.
그것은 IE8이 지원하는 텍스트에 그라디언트 스타일을 사용할 수있게 해줍니다!
여기서 라이브 데모를 찾을 수 있습니다. 원본 저장소는 GitHub뿐 아니라 오픈 소스에서도 몇 가지 업데이트를받을 준비가되었습니다 (: D)
이것은 인터넷상의 어느 곳에서나이 저장소를 언급하기 위해 처음으로 (예, 5 년 후에, 당신이 올바르게 들었습니다), 나는 그것에 대해 흥분하고 있습니다!