我有这个HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Float</title>
<link rel="stylesheet" href="Styles/style.css" />
</head>
<body>
<div class="header">
</div>
<div class="mainContent">
<div class="slideBar"></div>
<div class="content">
up
<div class="div1">
Hello
</div>
down
</div>
</div>
<div class="footer"></div>
</body>
</html>
这是我的css风格:
html, body {
margin:0px;
height:100%;
}
.header {
width:100%;
height:20%;
background-color:red;
border-radius:10px;
}
.footer {
width:100%;
height:20%;
background-color:green;
}
.mainContent {
width:100%;
height:60%;
}
.slideBar {
width:20%;
height:100%;
float:left;
background-color:blue;
}
.content {
width:80%;
height:100%;
float:right;
background-color:yellow;
}
.content .div1 {
border:2px solid black;
margin-left:10px;
}
这是结果:
hello
字的边框到达所有宽度。但我需要它只是围绕文本
答案 0 :(得分:4)
<div>
是一个块级元素,因此为了让它围绕其内容缩小,您需要使其像内联元素一样。在display: inline-block;
上设置.content .div1
会使其行为或多或少像内联元素,因此它适合内容。请参阅此处的示例:http://jsfiddle.net/6wZhe/
但是,您可能想要做的是更改<div>
标记<span>
标记,这是另一个多用途非语义容器,除了它是内联元素,而不是块级元素。
如果你仍然希望在<div>
之后添加一个<br />
元素,或者使用浮点数进行换行。
答案 1 :(得分:1)
将display:inline-block;
添加到.content .div1并在html中添加<br>
上方和下方:
答案 2 :(得分:1)
为其添加display: inline-block
。 http://jsfiddle.net/zhF4f/
Div是“块元素”(display:block
),这意味着它们占据其父宽度的100%。通过设置内联块,它只包装内容。
答案 3 :(得分:1)
你可以写display:inline-block;对于class = div1的div或将div替换为span。 Div是默认的块元素。如果使用文本,最好使用span - default inline元素。