html - 围绕字符串的中间字符居中文本

标签 html css centering typography html-input

我有一个包含一些文本的元素,并且希望以最中心的字符应位于元素中间的方式将文本居中放置在元素内。例如。给定字符串“iiiii|MMMMM”“|”是最中心的字符,但在非等宽字体中 - 如果正常居中 - 更靠左。 “|”无论其他字符的字符宽度如何,都应位于元素的中心。
该元素也是一个输入,所以我不能将字符串拆分成它的字符。

希望您有一些想法,在此先感谢您。

最佳答案

不剪切字符串就无法对齐字符。

var arr = [];

var text1 = document.querySelector('#text1');
var text2 = document.querySelector('#text2');

document.querySelector('#textInput').addEventListener("input", function(){
  arr = textInput.value.split('|')
	
  text1.innerText = arr[0] || ''
  text2.innerText = arr[1] || ''
})
.text-wrap{
  width: 400px;
  box-shadow: 0 0 3px orange;
  font-size: 0;
}
.text-wrap span {
  display: inline-block;
  font-size: 1rem;
}
.text-wrap span:nth-child(1n){
  width: calc(50% - 3px);
}
.text-wrap span:nth-child(2){
  width: 6px;
  text-align: center;
}
.text-wrap span:nth-child(1){
  text-align: right;
  text-indent: -99999px;
}
<div class="text-wrap">
    <span id="text1">aaaadddddddddddddddddddddddddddddddddddddddddddddddddddddd</span>
    <span>|</span>
    <span id="text2">bb</span>
</div>
<input type="text" id="textInput"/>

关于html - 围绕字符串的中间字符居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59573638/

相关文章:

css - 我怎样才能使 CSS 背景图像居中,就好像图像具有不同的宽度一样(不切断 bgimg)?

javascript - 溢出时页面上移 :hidden css property is set to <html> tag only in Firefox

html - 如何在不溢出文本且不扩展其他列的宽度的情况下在列标题中显示垂直文本

HTML/CSS : How to get text around image to fit when window is resized?

php - 使用 php 更改 css 值

javascript - 如何隐藏特定列表中的图像并使它们在其他列表中可见

html - 在 div 中包含表

javascript - 使用 attr 函数替换属性

html - 使 li 占据其内容的宽度,将它们居中,但将它们保持在不同的行上

html - 无论浏览器的大小如何,文本居中并在页面上对齐