목차
- letterSpacing 예제 - 글자 간격 지정
- letterSpacing 정의
- letterSpacing 구문
- letterSpacing 예제 - 요소의 마지막 글자 뒤 공백 제거
letterSpacing 예제 - 글자 간격 지정
<p id="hz">홈짱닷컴 Homzzang.com</p>
<button type="button" onclick="homzzang()">클릭</button>
<script>
function homzzang() {
document.getElementById("hz").style.letterSpacing = "15px";
}
</script>
결과보기
letterSpacing 정의
글자간 간격 지정.
1.
- 기본값 : normal
- 반환값 : 글자 간격을 나타내는 문자열
- CSS속성 : letter-spacing
- CSS버전 : CSS1
2.
모든 브라우저 지원.
letterSpacing 구문
반환
object.style.letterSpacing
설정
object.style.letterSpacing = "normal|length|initial|inherit"
[속성값]
normal
기본 간격 (기본값)
length (예: cm, mm, in, px, pt, pc 단위)
숫자가 클수록 간격이 넓어짐. (음수 가능)
- cf. line-height 속성 : 음수 불가능
- 글자를 다닥다닥 붙게 하려면 보통 -1px 지정
initial
이 속성의 기본값으로 설정.
inherit
부모 요소의 속성값 상속
letterSpacing 예제 - 요소의 마지막 글자 뒤 공백 제거
<style>
div {
display: inline-block;
border: 1px solid red;
letter-spacing: 10px;
}
</style>
<div id="hz">홈짱닷컴</div>
<script>
const hz = document.getElementById('hz');
const text = hz.textContent;
const lastChar = text[text.length - 1];
// 마지막 글자 대체할 span 요소 생성
const span = document.createElement('span');
span.textContent = lastChar;
span.style.letterSpacing = '0';
// 마지막 글자를 span요소로 대체
hz.textContent = text.slice(0, -1);
hz.appendChild(span);
</script>
결과보기
PS. jQuery 경우
<style>
div {
display: inline-block;
border: 1px solid red;
letter-spacing: 10px;
}
</style>
<div id="hz">홈짱닷컴</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
const hz = $('#hz');
const text = hz.text();
const lastChar = text[text.length - 1];
// span 요소 생성
const span = $('<span>').text(lastChar).css('letter-spacing', '0');
// 마지막 글자를 span 요소로 대체
hz.text(text.slice(0, -1)).append(span);
});
</script>
결과보기
관련글: 세크티 님 (230814) https://sir.kr/qa/508376