CSS 在 div 内水平居中 <p>,同时保持文本左对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13646452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:55:13  来源:igfitidea点击:

Horizontally center <p> within a div while keeping the text left-aligned

cssalignmenttext-alignment

提问by bravokiloecho

I have multiple divs with a fixed width containing <p>tags which contain various lengths of text.

我有多个具有固定宽度的 div,<p>其中包含包含不同长度文本的标签。

I want this text to remain left-aligned but if the text does not take up as much space as the div width, I would like to align this text centrally.

我希望此文本保持左对齐,但如果文本不占用与 div 宽度一样多的空间,我希望将此文本居中对齐。

I assume the best way of achieving this would be to horizontally center the <p>within the div while keeping the text left-aligned but I'm not sure how to do this.

我认为实现这一点的最佳方法是<p>在 div 内水平居中,同时保持文本左对齐,但我不知道如何做到这一点。

I have tried setting margin:0 auto;but the <p>always resizes to the width of the div (unless I tell it otherwise, but I don't want to do this because if the text runs for longer than the div I don't want to break it early...)

我试过设置margin:0 auto;<p>总是调整到 div 的宽度(除非我另有说明,但我不想这样做,因为如果文本运行时间比 div 长,我不想早点打破它。 ..)

I've set up a JSfiddle here to demonstrate: http://jsfiddle.net/VDhUa/

我在这里设置了一个 JSfiddle 来演示:http: //jsfiddle.net/VDhUa/

(Basically in this example I would like to "Lorem ipsum..." stuff to be centrally aligned without using text-align:center;)

(基本上在这个例子中,我希望“Lorem ipsum ...”的东西在不使用的情况下居中对齐text-align:center;

Any Help would be greatly appreciated.

任何帮助将不胜感激。

Thank you!

谢谢!

回答by qooplmao

Set your outer div to text-align: center;and your inner p's to display: inline-block;

将外部 div 设置为text-align: center;,将内部 p 设置为display: inline-block;

Fiddle: http://jsfiddle.net/ZL4GM/

小提琴:http: //jsfiddle.net/ZL4GM/