宽度等于内容 [英] Width equal to content

查看:60
本文介绍了宽度等于内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用CSS的width属性时遇到了一些麻烦.我在div中有一些段落.我想使段落的宽度等于它们的内容,以使它们的绿色背景看起来像文本的标签.相反,我得到的是这些段落继承了div父节点的宽度,该宽度更宽.

I'm experiencing some trouble with the width property of CSS. I have some paragraphs inside a div. I'd like to make the width of the paragraphs equal to their content, so that their green background looks like a label for the text. What I get instead is that the paragraphs inherit the width of the div father node which is wider.

#container {
  width: 30%;
  background-color: grey;
}

#container p {
  background-color: green;
}

<div id="container">
  <p>Sample Text 1</p>
  <p>Sample Text 2</p>
  <p>Sample Text 3</p>
</div>

推荐答案

默认情况下,p标记是block元素,这意味着它们占据了父级width的100%.

By default p tags are block elements, which means they take 100% of the parent width.

您可以通过以下方式更改其显示属性:

You can change their display property with:

#container p {
   display:inline-block;
}

但是它将元素并排放置.

But it puts the elements side by side.

要使每个元素保持独立行,可以使用:

To keep each element on its own line you can use:

#container p {
   clear:both;
   float:left;
}

(如果您使用float并需要在浮动元素之后清除,请参见此链接以了解不同的技术: http://css-tricks.com/all-about-floats/)

演示: http://jsfiddle.net/CvJ3W/5/

Demo: http://jsfiddle.net/CvJ3W/5/

修改

如果您使用display:inline-block寻求解决方案,但想将每一项都保留在一行中,则只需在每一项之后添加一个<br>标记即可:

If you go for the solution with display:inline-block but want to keep each item in one line, you can just add a <br> tag after each one:

<div id="container">
  <p>Sample Text 1</p><br/>
  <p>Sample Text 2</p><br/>
  <p>Sample Text 3</p><br/>
</div>

新演示: http://jsfiddle.net/CvJ3W/7/

New demo: http://jsfiddle.net/CvJ3W/7/

这篇关于宽度等于内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆