簡體   English   中英

如何在絕對定位的列表元素中使文本居中對齊?

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

我有以下代碼,

 .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> 

我想將文本內容放在推薦容器內。 我嘗試了p {text-align: center} ,但無濟於事。 我注意到當li的位置不是絕對時, text-align: center起作用了。

我缺少什么,我該如何糾正?

如果您只想使用當前解決方案而不使用flexbox將其居中,則該方法應該起作用,當絕對定位一個元素時,它將不再具有某些默認屬性,例如width:100%才能正常工作。

希望能幫助到你!

 .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> 

您出現問題的原因是因為li的absolute寬度不absolute

所以這是一種實現您想要的方式

 .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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM