如何创建右列宽度固定的两列 Div 布局?
<div> 元素是 HTML 中使用最广泛的元素之一。"<div>"指的是将页面划分为多个部分的容器。这些部分对于将元素分组非常有用。<div> 元素本身并没有视觉呈现,但当我们想要将自定义样式应用于 HTML 元素时,它们非常有用。它们允许我们将元素分组,以便对其中的所有元素应用相同的样式。我们还可以对整个 div> 元素进行样式设置。使用 class 或 id 属性可以轻松实现样式设置。
示例
这是一个展示 div 标签用途的简单示例。
<html>
<head>
<style>
.div1{
background-color:lightblue;
width:300px;
height:75px;
margin-bottom:-16px;
}
.div2{
background-color:lightpink;
width:300px;
height:30px;
margin:0px;
}
</style>
</head>
<body>
<div class="div1">
<p>DIV 1</p>
</div>
<div class="div2">
<p>DIV 2</p>
</div>
</body>
</html>
我们也可以让两个 div 元素相邻。这被称为 双列 div 布局。这可以通过使用 CSS float 属性来实现。
CSS float 属性将元素定位到其容器的左侧或右侧,允许文本和内联元素环绕它。该元素将脱离页面的正常流,但仍保留在流中。float 属性可以通过一个关键字指定,该关键字的值包括 left、right、none、inline-start 和 inline-end。
示例
以下示例展示了如何借助 float 属性创建双列 div 布局。
<html>
<head>
<style>
.div1{
background-color:lightblue;
width:300px;
height:75px;
margin-bottom:-16px;
float:left;
}
.div2{
background-color:lightpink;
width:100%;
height:75px;
margin:0px;
}
</style>
</head>
<body>
<div class="container">
<div class="div1">
<p>DIV 1</p>
</div>
<div class="div2">
<p>DIV 2</p>
</div>
</div>
</body>
</html>
div 元素的高度和宽度可以根据需求调整,也可以固定为某个尺寸。
在本教程中,我们将讨论如何创建两列 div 布局,其中右列具有固定宽度。
使用 CSS 浮动和宽度属性
如前所述,浮动属性用于定位和格式化内容。它可以用于将任何内联元素包裹在指定的 HTML 元素周围,例如列表、段落、div、span、表格、iframe 和块引用。
宽度属性指定元素的宽度。它默认决定内容区域的宽度,但如果 box-sizing 设置为 border-box,则它决定边框区域的宽度。
我们可以创建一个两列的 div 布局,右列宽度固定,方法是设置右列的 float 和 width 属性,同时确保左列没有 width 和 float。
示例
在下面的示例中,我们将右列的 float 属性设置为 right,使其以预定义的固定宽度浮动到容器的右侧。左列的宽度设置为 auto,允许浏览器计算宽度。
<!DOCTYPE html>
<html>
<head>
<title>
How to Create a Two-Column Div Layout with the Right Column Having Fixed Width?
</title>
<style>
body{
margin:20px;
}
.container {
height: auto;
overflow: hidden;
}
.div2 {
width: 150px;
height:50px;
float: right;
background: darkcyan;
}
.div1 {
height:50px;
width: auto;
overflow: hidden;
background:turquoise;
}
p{
margin-top:15px;
margin-left:20px;
font-size:20px;
color:white;
}
</style>
</head>
<body>
<div class="container">
<div class="div2">
<p>DIV 2</p>
</div>
<div class="div1">
<p>DIV 1</p>
</div>
</div>
</body>
</html>
上面的示例需要将右列放在左列之前。但是,如果我们想遵循正确的 HTML 标记,可以尝试下面的示例。
示例
以下示例可以帮助我们创建两列的 div 布局,而无需调整 HTML 标记。
<html>
<head>
<title>How to Create a Two-Column Div Layout with the Right Column Having Fixed Width?
</title>
<style>
body{
margin:30;
background:lightblue;
}
.container {
width: 100%;
background: lavender;
float: left;
margin-right: -200px;
}
.div1 {
background: lavenderblush;
margin-right: 155px;
border:3px solid purple;
}
.div2 {
width: 150px;
float: right;
border:3px solid purple
}
p{
margin-left:10px;
}
</style>
</head>
<body>
<div class="container">
<div class="div1">
<p>DIV 1</p>
</div>
</div>
<div class="div2">
<p>DIV 2</p>
</div>
</body>
</html>
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

