2013-06-18 25 views
8

这是交易。我不想仅在我的段落中加下划线,而是使用text-align,我想在下面添加一个虚线边框,并将它居中在段落的父节点div内。这是我的代码不起作用。 (它增加了边界在整个div而不只是段)如何在CSS中自动设置段落宽度?

p { 
    border-bottom:1px dotted; 
    margin-left:auto; 
    margin-right:auto; 
    text-align:center; 
} 

该段似乎正在父div的宽度。有没有办法将段落的宽度设置为它包含的文本? (看来,margin:auto会如果可能的工作。)

回答

28

段落打算扩大其集装箱的宽度。为了使它不这样做,你可以尝试:

p { display: inline-block; } 

拨弄例如:http://jsfiddle.net/HuFZL/1/

此外,您可能要包裹p标签附加div,如果你需要他们清除其他段落/元素。

+0

正是我在找的,谢谢。 – user2020058

+3

display:table更高效,并且不需要将它们作为内联框,然后将它们包装到div中 –

+0

我不知道有关display:table和size的问题。以前我一直针对IE7,所以我对它有点无知。谢谢! – SlightlyCuban

1

尝试增加宽度值的段落里,否则该段将填补父容器的整个宽度和边距值将不会做任何事情:

p { 
    border-bottom:1px dotted; 
    margin-left:auto; 
    margin-right:auto; 
    text-align:center; 
    width: 100px; /* whatever width you want */ 
} 
+0

感谢您的答复,但对于一个小段落,这将会使边框长于文本。我正在寻找边框的方式,只能跨越文本的宽度。 – user2020058

+0

最大宽度值而不是指定宽度如何?你可以发布你的所有代码或制作小提琴吗? –

0

这就是我想....

<html> 

<style> 
{ 
border-bottom:1px dotted; 
margin-left:auto; 
margin-right:auto; 
text-align:center; 
} 

#custom 
{ 
width : 10px; 
} 

</style> 

<div id="custom"><p>dddd</p></div> 

</html> 
4

,如果你想段落保持堆叠在对方,并从他们成长的内容,你应该需要的是:

p { 
     display: table; 
     margin:auto; 
     border-bottom:1px dotted; 
} 
0

没有,保证金自动不会更改段落元素的大小。它只是试图自动确定元素的自动尺寸边上适当的边距尺寸。基本上,如果您希望段落比包含它的div小,您可以将段落的静态宽度设置为特定宽度或父元素内部宽度的百分比。另一个选项,如果你不想做任何静态大小的段落(S)将设置填充父元素或设置静态页边距(S)。

div.paragraph-container { 
    padding: 20px; /* or padding: 20px 20px 20px 20px; sets all the padding individually (top, right, bottom, left) */ 
} 

这将使格内的所有段落中心,是40像素较小假设段落没有利润。

div.paragraph-container p { 
    margin: 10px 20px; /* sets the margin on the paragraph(s) to 10px on top and bottom and 20px on left and right which does the same as the first example assuming that the div does not have padding. */ 
} 

如果你想在边境成为完全文本的宽度则:

div.paragraph-container p { 
    border-bottom: 1px dotted black; 
    padding: 0px 0px 5px 0px; 
    margin: 10px 20px; 
} 

div.paragraph-container { 
    padding: 0px; 
} 

假设文字填满段落元素,那么这将正常工作。如果你在段落中有两个单词,那么它不会只与文本一样宽。解决这个问题的唯一方法是使用内联元素,例如跨度或已设置为display: inline;的元素,但内联元素将会并排混乱,除非在它们之间放置块元素。

+0

谢谢您添加语法高亮显示,@Hemerson。现在我知道该怎么做了。 – txpeaceofficer09

0

防弹方式

HTML

<div class="container"> 
<p><p> 
</div> 

CSS

.container { text-align:center; } 
.container p { 
    display: table; 
    margin:0 auto; 
    display: inline-block; 
    zoom: 1; 
    *display: inline; 
} 
+1

不会第二次显示值覆盖第一个? – Izzy