22

这是交易。我不只是在我的段落下划线并使用text-align,而是想在下面添加一个虚线边框并将其居中在段落的 parent 内div。这是我的代码不起作用。(它在整个div而不只是段落上添加边框)

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

该段落似乎占用了 parent 的宽度div。有没有办法将段落的宽度设置为它包含的文本?(如果可能的话,这似乎margin:auto可行。)

4

7 回答 7

52

段落将扩展到其容器的宽度。为了让它不这样做,你可以尝试:

p { display: inline-block; }

摆弄示例:http: //jsfiddle.net/HuFZL/1/

此外,如果您需要它们以清除其他段落/元素,您可能希望将p标签包装在附加的 中。div

于 2013-06-18T17:59:49.053 回答
5

如果您希望段落彼此堆叠并从其内容中增长,您应该需要的是:

p { 
      display: table;
      margin:auto;
      border-bottom:1px dotted;
}
于 2013-06-18T18:11:34.003 回答
1

尝试为段落添加宽度值,否则段落将填满父容器的整个宽度,并且边距值不会做任何事情:

p {
  border-bottom:1px dotted;
  margin-left:auto;
  margin-right:auto;
  text-align:center;
  width: 100px; /* whatever width you want */
}  
于 2013-06-18T17:51:57.253 回答
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>
于 2013-06-18T17:53:54.890 回答
0

不,margin auto 不会改变段落元素的大小。它只是尝试在元素的自动调整大小的边上自动确定适当的边距大小。基本上,如果您希望段落小于包含它的 div,您可以将段落的静态宽度设置为特定宽度或父元素内部宽度的百分比。如果您不想对段落进行任何静态调整大小,另一种选择是在父元素上设置填充或在段落上设置静态边距。

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

假设段落没有边距,这将使所有段落在 div 内居中并小 40px。

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;
}

假设文本填充段落元素,那么这将起作用。如果段落中有 2 个单词,那么它就不会和文本一样宽。实现这一点的唯一方法是使用像 span 这样的内联元素或设置为 的元素display: inline;,但内联元素会并排混乱,除非你在它们之间放置一个块元素。

于 2013-06-18T18:19:07.543 回答
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; 
}
于 2014-02-17T14:16:48.250 回答
0

您可以使用 span 自动设置宽度。

我想它一定不是一个段落?

CSS:

.container {
   width: 100%;
   height: auto;
   background: #ff0000;
   text-align: center;
}

.myText {
   width: auto;
   background: #ffff00;
}

HTML:

<div class="container">
    <span class="myText">Hello</span>
</div>
于 2018-09-21T14:24:02.433 回答