CSS:设置宽度等于内容 [英] CSS: set width equal to content
问题描述
我遇到了一些麻烦与CSS的width属性。我在div里面有一些段落。我想设置段落的宽度等于它们的内容,以便他们的绿色背景看起来像文本的标签。我得到的是,段落继承了更宽的div父节点的宽度。我应该做什么?
谢谢。
HTML:
div id =container>
< p>示例文字1< / p>
< p>示例文本2< / p>
< p>示例文本3< / p>
< / div>
CSS:
code> #container {
width:30%;
background-color:gray;
}
#container p {
background-color:green;
}
c> p 标签是 block
元素,这意味着它们占用父 >。
您可以使用以下方式更改其显示属性:
#container p {
display:inline-block;
}
但它会将元素并排。
要使每个元素保持不变,您可以使用:
#container p {
clear:both;
float:left;
}
(如果使用float并且需要在浮动元素之后清除,请参阅此链接了解不同的技术: http://css-tricks.com/all-about-floats / >
演示: http://jsfiddle.net/CvJ3W/5/
编辑 >
如果你想使用 display:inline-block
的解决方案,但希望将每个项目保持在一行,在每一个之后添加< br>
标记:
div id =container>
< p>示例文字1< / p>< br />
< p>示例文字2< / p>< br />
< p>范例文字3< / p>< br />
< / div>
新演示: http://jsfiddle.net/CvJ3W/7/
I'm experiencing some troubles with the width property of CSS. I have some paragraphs inside a div. I'd like to set 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. What I am supposed to do? Thank you.
HTML:
<div id="container">
<p>Sample Text 1</p>
<p>Sample Text 2</p>
<p>Sample Text 3</p>
</div>
CSS:
#container {
width: 30%;
background-color: grey;
}
#container p{
background-color: green;
}
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;
}
(If you use float and need to clear after floated elements, see this link for different techniques: http://css-tricks.com/all-about-floats/)
Demo: http://jsfiddle.net/CvJ3W/5/
Edit
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>
New demo: http://jsfiddle.net/CvJ3W/7/
这篇关于CSS:设置宽度等于内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!