CSS 布局技巧:
- 浮动(Float):
应用场景:浮动最初应用于创建多列布局,特别是在早期的网页开发中。但是,现在浮动更多地用于在文字周围环绕图片或其他元素。
实操实践:使用float属性可以将元素浮动到左侧或右侧,使其他元素环绕在其周围。要使浮动的元素正常布局,需要清除浮动来确保其周围的元素正确排列。
- 定位(Positioning):
应用场景:定位布局非常适合创建自定义的、特殊效果的页面布局,如悬浮元素、覆盖内容等。它允许你准确地控制元素在页面上的位置。 实操实践:使用 position 属性可以设置元素的定位方式,如 relative、absolute、fixed 等。通过设置 top、right、bottom、left 属性,你可以精确地确定元素在页面中的位置。
- 弹性盒子布局(Flexbox):
应用场景:弹性盒子布局是一种强大的工具,适用于创建灵活的、自适应的布局。它特别适用于构建导航、列表和居中元素等复杂布局。 实操实践:通过将父元素的 display 属性设置为 flex,你可以创建一个弹性盒子容器。然后,使用诸如 flex-direction、justify-content、align-items 等属性来控制子元素的排列方式。
<html>
<head>
<style>
body {
width: 90%;
max-width: 900px;
margin: 0 auto;
height: 1400px;
}
.floatContainer1 {
overflow: hidden;
}
.column {
margin-top: 3rem;
width: 50%;
float: left;
box-sizing: border-box;
padding: 20px;
border: 1px solid #ddd;
}
.box {
float: left;
margin-right: 15px;
width: 200px;
height: 150px;
border-radius: 5px;
background-color: rgba(207, 232, 220, 0.3);
padding: 1em;
}
.positionFixed h1 {
position: fixed;
top: 0;
width: 100%;
margin: 0 auto;
background: white;
padding: 13px;
}
dt {
background-color: black;
color: white;
padding: 10px;
position: sticky;
top: 70;
left: 0;
margin: 1em 0;
}
.flexContainer {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
height: 200px;
flex: 200px;
}
.flexContainer div {
margin: 20px;
padding: 30px;
background-color: #4287f5;
color: white;
}
</style>
</head>
<body>
<div>
<dl>
<dt>Float 实现双栏布局</dt>
<dd>
<div class="floatContainer1">
<div class="column">
<h5>Column 1</h5>
<p>This is the left column content.</p>
</div>
<div class="column">
<h5>Column 2</h5>
<p>This is the right column content.</p>
</div>
</div>
</dd>
<dt>Float实现浮动元素</dt>
<dd>
<div class="floatContainer2">
<div class="box">Float</div>
<p style="background-color: bisque">
I am a basic block level element. My adjacent block level elements
sit on new lines below me.
</p>
<p>
We are separated by our margins. Because of margin collapsing, we
are separated by the width of one of our margins, not both.
</p>
<p style="clear: left">
I am a basic block level element. My adjacent block level elements
sit on new lines below me.
</p>
<p>
We are separated by our margins. Because of margin collapsing, we
are separated by the width of one of our margins, not both.
</p>
</div>
</dd>
<dt>Position Fixed实现标题</dt>
<dd>
<div class="positionFixed">
<h1>总标题</h1>
</div>
</dd>
<dt>Position Sticky 滚动索引</dt>
<dd><div class="positionSticky"></div></dd>
<dt>flex布局</dt>
<dd>
<div class="flexContainer">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
</div>
</dd>
</dl>
</div>
</body>
</html>