gpt4 book ai didi

css - 中心文本大于容器? (不使用单独的子元素)

转载 作者:技术小花猫 更新时间:2023-10-29 10:36:41 26 4
gpt4 key购买 nike

使用 CSS,可以很容易地使用 text-align:center; 在容器中水平居中文本,但是如果该文本中的任何一个单词大于容器的宽度,浏览器会自动“剪裁”到容器的左边界(例如,超大的单词与太小容器的左侧,并且没有 CSS word-break:hyphenate; 属性设置(或类似设置),过大的字会超出容器的右边缘。

enter image description here有什么方法可以将这张照片 float 到我的文字左侧以节省垂直空间?那好吧。无论如何...

使用子容器元素来保存文本,有没有办法将过大的字居中,以便它悬在文本的左右两侧容器同样?

同样,我不想在容器内使用文本容器。我可以用 child 在 5 秒内完成 <div>text to be centered</div>固定 width和负面 margin-left , 或者用 absolute容器元素在 relative 中的定位div ,但我正在寻找一个 CSS 属性,即使单词太长而无法适应宽度,它也会使文本居中。默认情况下,text-align:center不这样做。

想法?谢谢! -Slink

最佳答案

This fiddle显示三个 div 元素说明“问题”和以下两个“解决方案”。

一个可能的“解决方案”

我不确定您的需求,但到目前为止,我找到的唯一真正的解决方案是将 display: table 设置为您的文本容器。但这将允许容器拉伸(stretch)到所需的宽度以包含最长的单词,这可能不是您所希望的。如果没问题,那就是最好的解决方案。

另一种可能的“伪造”解决方案

如果您必须至少保持元素的外观大小,那么您可以通过一些创造性的伪元素使用来伪造外观:

.fakeIt {
text-align: center; /* what you wanted all along */
display: table; /* key to get centered */
position: relative; /* allow reference for absolute element */
z-index: 2; /* set up for a background to be pushed below */
width: 40px; /* what you want, but table resizes larger if needed*/
border: none; /* transferring border to the "fake" */
background-color: transparent; /* transferring background to the "fake" */
}

.fakeIt:after {
content: ''; /* before or after need it, even if empty */
width: 40px; /* the original width you wanted for the container */
position: absolute; /* need this to position it */
z-index: -1; /* push it behind the foreground */
left: 50%; /* push it to center */
top:0; /* give it height */
bottom: 0; /* give it height */
margin-left: -20px; /* half the width to finish centering */
border: 1px solid red; /* the border you wanted on the container */
background-color: yellow; /* the background you wanted on the container */
}

但是,根据您的特定应用,“伪造”的解决方案可能不起作用。此外,原始元素仍将占据文档中更宽的“空间”,只是看起来不像了。这可能会导致问题。容器上的负 margin 可以解决这个问题,但您不知道需要将值设置为多少,因为它会因文本宽度而异。

你在评论中提到你不熟悉 css 中的伪元素,所以你可能 want to have a quick intro .

关于css - 中心文本大于容器? (不使用单独的子元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11438380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com