web-dev-qa-db-ja.com

CSSで段落幅を自動的に設定するにはどうすればよいですか?

これが取引です。段落に下線を付けてtext-alignを使用する代わりに、下に点線の境界線を追加し、段落の親divの中央に配置します。これは機能していない私のコードです。 (段落だけでなく、div全体に境界線を追加します)

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

段落は親divの幅をとっているようです。段落の幅をそれに含まれるテキストに設定する方法はありますか? (margin:autoは可能であれば機能するようです。)

15
user2020058

段落はコンテナの幅まで拡大します。それを行わないようにするには、次を試してください:

p { display: inline-block; }

例の工夫: http://jsfiddle.net/HuFZL/1/

また、他の段落/要素をクリアする必要がある場合は、pタグを追加のdivでラップすることもできます。

37
SlightlyCuban

段落が互いに重なり合って、その内容から成長するようにする場合、必要なものは次のとおりです。

p { 
      display: table;
      margin:auto;
      border-bottom:1px dotted;
}
5
G-Cyr

段落に幅の値を追加してください。追加しないと、段落が親コンテナの幅いっぱいになり、マージンの値は何もしません。

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

いいえ、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;に設定された要素を使用することですが、ブロック要素を間に配置しない限り、インライン要素は並んで混乱します。

0

スパンを使用して、幅を自動的に設定できます。

私はそれが段落であってはならないと思う?

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>
0
Elias

これは私が試したものです....

<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>
0
psniffer

防弾方法

[〜#〜] 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; 
}
0
comonitos