简体   繁体   中英

How to align text to center in an absolutely positioned list element?

I have the following code,

 .testimonial-wrapper { background: green; } .testimonial { max-width: 980px; height: 70px; margin: auto; overflow: hidden; background: grey; } li { list-style: none; height: 70px; } .testimonial { position: relative; } li { position: absolute; top: 70px; } li.current{ top: 0; } 
 <div class="testimonial-wrapper"> <div class="testimonial"> <ul> <li class="current"><div> <p>This is the first test message</p> </div> </li> <li> <div> <p>I have nothing more to say</p> </div></li> <li><div> <p>again if i could i would</p> </div> </li> </ul> </div> </div> 

I would like to center the text content within the testimonial container. I tried p {text-align: center} , but to no avail. I noticed that when the li is not absolutely positioned, the text-align: center worked.

What am I missing, and how can I correct this?

This should work if you just want to center it using current solution without using flexbox, when an element is absolutely positioned, it will no longer have some default properties such as width: 100% for it to works.

Hope it helps!

 .testimonial-wrapper { background: green; } .testimonial { max-width: 980px; height: 70px; margin: auto; overflow: hidden; background: grey; } li { list-style: none; height: 70px; } .testimonial { position: relative; } li { position: absolute; top: 70px; text-align: center; width: 100%; } li.current{ top: 0; } ul { list-style: none; padding-left: 0; } 
 <div class="testimonial-wrapper"> <div class="testimonial"> <ul> <li class="current"><div> <p>This is the first test message</p> </div> </li> <li> <div> <p>I have nothing more to say</p> </div></li> <li><div> <p>again if i could i would</p> </div> </li> </ul> </div> </div> 

The cause of your problem is the li not taking the full width as it is positioned absolute

So here's a way to achieve what you want

 .testimonial-wrapper { background: green; } .testimonial { max-width: 980px; height: 70px; margin: auto; overflow: hidden; background: grey; position: relative; } li { list-style: none; height: 70px; } .testimonial { position: relative; } li { position: absolute; left: 0; top: 70px; width: 100%; text-align: center; } li.current{ top: 0; } 
 <div class="testimonial-wrapper"> <div class="testimonial"> <ul> <li class="current"><div> <p>This is the first test message</p> </div> </li> <li> <div> <p>I have nothing more to say</p> </div></li> <li><div> <p>again if i could i would</p> </div> </li> </ul> </div> </div> 

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