简体   繁体   中英

One-line text not aligned to center of div

For divs with multi-line titles the text is aligned perfectly to the center. However for single-line titles this is not the case (even with text-align set to center). The text aligns itself to the left border of the parent span. Seems absolutely trivial but have not managed to get it right.

 span.text-content { background: rgba(255,255,255,0.5); color: white; cursor: pointer; display: inline-block; height: 100%; left: 0; position: absolute; top: 0; width: 100%; opacity:0; } span.text-content span { display: table-cell; text-align: center; vertical-align: middle; color: #000; font-weight: 900; text-transform: uppercase; position:absolute; top: 45%; } 
 <span class="text-content"><span>Post Title</span></span> 

Here is the fix using your code (i changed the background color and opacity so I could see it).

Main changes were to make parent display: table and to give the child span a width of 100% so that your text-align would work.

 span.text-content { background-color: white; color: white; cursor: pointer; display: table; height: 100%; left: 0; position: absolute; top: 0; width: 100%; } span.text-content span { display: table-cell; width: 100%; text-align: center; vertical-align: middle; color: #000; font-weight: 900; text-transform: uppercase; position:absolute; top: 45%; } 
 <span class="text-content"><span>Post Title</span></span> 

Weave: http://kodeweave.sourceforge.net/editor/#fe0c9da444a8df390c6242afa00f0bb3

It's a simple fix!

When using display table-cell the parent element must be display table .

NOTE: By default span elements are display inline .

To make your text centered horizontally you need to have text-align center (in this case on the parent of table-cell .

Also in this case you don't need position (or top) applied to table-cell because using vertical-align middle already centers your text vertically on the table-cell .

In addition your span.text-content is overqualified just use .text-content instead.

BTW: I removed opacity on .text-content so I could see the text.

 .text-content { cursor: pointer; display: table; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.5); color: white; text-align: center; } .text-content span { display: table-cell; vertical-align: middle; color: #000; font-weight: 900; text-transform: uppercase; } 
 <span class="text-content"> <span>Post Title</span> </span> 

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