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

Sli*_*ink 10 css text centering

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

在此输入图像描述有什么方法可以将这张照片留在我的文字左边以节省垂直空间?那好吧.无论如何...

如果不使用子容器元素来保存文本,是否有办法将超大字体居中,以便它同样悬挂在容器的左右两侧?

同样,我不想在容器中使用文本容器.我可以通过使用<div>text to be centered</div>具有固定width和负数的子项margin-left,或者absolute在a中定位容器元素,在5秒内完成此操作relative div,但我正在寻找一个CSS属性,即使单词太长而无法适应宽度,也会使文本居中.默认情况下,text-align:center不执行此操作.

思考?谢谢!-Slink

Sco*_*ttS 11

这个小提琴显示了三个div元素,说明了"问题"和以下两个"解决方案".

可能的"解决方案"

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

另一种可能的"假"解决方案

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

.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 */
}
Run Code Online (Sandbox Code Playgroud)

但是,根据您的特定应用,"伪造"解决方案可能无效.此外,原始元素仍将占据文档中更宽的"空间",它看起来不会像现在这样.这可能会导致问题.margin容器上的否定可以解决这个问题,但是您不知道需要设置什么值,因为它会随文本宽度而不同.

你在评论中提到你不熟悉css中的伪元素,所以你可能想要快速介绍.