html - css如何为内容设置div宽度

标签 html css

我有这个 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;
    }

这是结果: enter image description here

我的问题

hello 单词的边框达到所有宽度。但我只需要它包围文本

最佳答案

<div>是一个 block 级元素,所以为了让它围绕它的内容收缩,你需要让它表现得像一个内联元素。设置display: inline-block;.content .div1将使它的行为或多或少像一个内联元素,因此它适合内容。请参阅此处的示例:http://jsfiddle.net/6wZhe/

但是,您可能想要做的是更改您的 <div> <span> 的标签标签,这是另一个多用途的非语义容器,除了它是一个内联元素,而不是 block 级元素。

如果你还想在 <div> 之后换行你可以添加 <br />元素,或使用 float 。

关于html - css如何为内容设置div宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23157874/

相关文章:

html - 我可以在 CSS 文件中指定变量名吗

html - 响应时导航栏标题不正确且位于菜单栏下方

html - 将下拉菜单添加到现有导航菜单

javascript - 在表单中选择单选按钮时如何显示和隐藏div?

html - CSS:图形居中,然后向右继续一个模式

html - 无论浏览器缩放级别如何,如何使图像排成一行?

html - float 元素落在另一个 float 元素下方

HTML 表格边框现在显示在 asp.net mvc 3 View 中

html - 防止 Div 在包装后填充父 Div 宽度

javascript - iframe 中的附加字符串被复制