是否有一种简单的方法可以使文本水平居中,即使在很长的单词需要延伸到周围的填充中时也可以使用?
例如,以下内容:
的HTML
<section>
<p>
Some animals in the wild, like
hummingbirds, have long names.
</p>
</section>
的CSS
section p {
width: 75px;
text-align: center;
background: gold;
padding: 20px;
}
导致“蜂鸟”偏离中心:
如果将“蜂鸟”一词正确居中,它将很好地适合金盒。
摆弄它:https :
//jsfiddle.net/m6h37q2z/
补充说明1:
此问题不是关于如何删除填充或减小字体大小或使框变大的问题……这些都是非常容易的调整(会破坏设计)。这个问题是关于如何使“蜂鸟”一词居中。
补充说明2:
对于那些说没有足够空间的人,这是一张经过照片处理的屏幕截图,证明有足够的空间:
这是另一种使用负数的方法,letter-spacing
并使用jQuery来检测长字(超过8个字符),并将它们包装在以负数margin
和为中心的特殊范围内display: block
:
$('section p').each(function() {
var p = $(this);
var text = p.text();
var words = text.split(' ');
p.empty();
$.each(words, function(i, w) {
if (this.length > 8) {
p.append("<span>" + this + "</span>");
} else {
p.append(w + ' ');
}
});
});
body { font-family: sans-serif; }
section p {
width: 75px;
text-align: center;
background: gold;
padding: 20px;
letter-spacing: -0.4px;
float: left;
margin-right: 40px;
}
section p span {
display: block;
margin:0 -200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<p>Some animals in the wild, like hummingbirds, have long names.</p>
<p>Some animals in the wild, like oxen, have short names.</p>
<p>Some animals in the wild, like varylawngstrung, have short names.</p>
<p>Hellooooo my nameee isssssss whaaaaaaaaaaaaaaat</p>
</section>
https://jsfiddle.net/azizn/bf52mwgr/
另外,如果您想弄乱长字,可以使用以下代码,它将弄乱长于15个字符的字并恢复inline
显示:
$('section p').each(function() {
var p = $(this);
var text = p.text();
var words = text.split(' ');
p.empty();
$.each(words, function(i, w) {
if (this.length > 8 && this.length < 16) {
p.append("<span>" + w + " </span>");
} else if (this.length > 15) {
p.append("<span class='break'>" + w + " </span>");
} else {
p.append(w + ' ');
}
});
});
body { font-family: sans-serif; }
section p {
width: 75px;
text-align: center;
background: gold;
padding: 20px;
letter-spacing: -0.4px;
float: left;
margin-right: 40px;
}
section p span {
display: block;
margin: 0 -200px;
}
section p span.break {
display: inline;
margin: 0;
word-break: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<p>Some animals in the wild, like hummingbirds, have long names.</p>
<p>Some animals in the wild, like hummingbirdsss, have long names.</p>
<p>Some insects in the wild, like Parastratiosphecomyia, have huge names.</p>
</section>
jsFiddle:https ://jsfiddle.net/azizn/8w3w2zh1/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句