简体   繁体   中英

Center text around a specific word

In CSS, how can I center text around a specific word?

For instance, let's say I have the following DIV :

<div style="text-align: center;">
  Previous Day | Navigation | Next Day
</div>

The text will technically be centered, but the word "Navigation" will NOT be in the exact middle. Rather, the middle will be exactly between the letters "v" and "i". This is because when centering text, the length of the entire string is taken into account.

How can I make the middle instead be between the "g" and the "a", using (preferably) only CSS? Modifying the HTML is also acceptable. As a last resort, I'm willing to use JavaScript, although only if it's kept simple, otherwise it's not worth it to use complex JavaScript for such a simple task.

Fixing the width of the elements containing "Previous Day" and "Next Day" is probably the simplest solution:

<div style="text-align: center;">
    <div style="display: inline-block; width: 12em; text-align: right;">Previous Day</div>
    <div style="display: inline-block;"> | Navigation | </div>
    <div style="display: inline-block; width: 12em; text-align: left;">Next Day</div>
</div>

Fiddle here .

You can wrap your individual items in an HTML tag, like an anchor, and float them to achieve your desired result. Floating the tags places them side-by-side, and giving each item a percentage-width that collectively adds to 100% effectively centers the elements in their container.

Note, there are some pitfalls to using floats. You need to clear the parent div to properly lay out elements following a container with floated children. Also, if the child elements have any padding, this will be added to the percentage width and misalign the children unless you use box-sizing: border-box; on the child elements.

HTML

<div class="container">
    <a href="#">Previous Day</a>
    <span class="separator">|</span>
    <a href="#">Navigation</a>
    <span class="separator">|</span>
    <a href="#">Next Day</a>
</div>

CSS

.container {
    color: white;
    margin: 0 auto;
    width: 80%;
    min-width: 320px;
    background-color: black;
    overflow: hidden; /* to clear the div */
}

.container a {
    text-align: center;
    float: left;
    width: 32%;
    overflow: hidden;
    background-color: orange;
}

.container .separator {
    float: left;
    text-align: center;
    padding: .5%;
}

The colors are to show that it is centered in its parent element.

Here's a live demo jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM