Center Text Larger than Container? (Without using separate child element)

爱⌒轻易说出口 提交于 2019-12-03 06:17:25
ScottS

This fiddle shows three div elements illustrating the "problem" and both the following "solutions".

One Possible "Solution"

I'm not sure of your needs, but so far the only real solution I have found is to set display: table to your text container. But that will allow the container to stretch to the needed width to contain the longest word, which may not be desirable to you. If that is okay, that is the best solution.

Another Possible "Faked" Solution

If you must keep the apparent size of the element at least, then you can fake the look by some creative pseudo-element use:

.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 */
}

However, depending upon your particular application, the "faked" solution may not work. Also, the original element will still take up the wider "space" in the document, it just won't look like it is. That could cause issues. Negative margin on the container could solve that, but you don't know what the value needs to be set at, as it would differ with text width.

You mention in a comment you are not familiar with pseudo-elements in css, so you may want to have a quick intro.

That damned horizontal scrollbar!

http://jsfiddle.net/sqKU6/

<div class="inner">
    aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa 
</div>
​

CSS:

.inner {
    text-align: center;
    position: relative;
    left: +450%;
}
.inner:before {
    content: '';
    display: inline-block;
    margin-right: -900%;
}
​

I use this solution:

.limited-string {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 90%;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!