首页 / 预测世界杯足球

Div属性方法与布局速查表

2025-11-11 10:10:53预测世界杯足球 3731

Div 属性、方法与布局速查表(HTML/CSS)

一、Div 核心属性

1. HTML 属性

属性说明示例id唯一标识符

class类名(用于CSS选择器)
style内联样式
title鼠标悬停提示文本

2. CSS 核心属性

属性说明值类型示例display显示模式block/inline/flexdisplay: flex;position定位方式static/relative/absolute/fixedposition: relative;width宽度px/%/autowidth: 100%;height高度px/%/autoheight: auto;margin外边距px/automargin: 20px;padding内边距px/autopadding: 10px;box-sizing盒子模型border-box/content-boxbox-sizing: border-box;

二、Div 操作方法(JavaScript)

1. DOM 操作

// 获取元素

const div = document.getElementById('myDiv'); // id选择器

const divs = document.querySelectorAll('.container div'); // 类选择器+后代

// 修改样式

div.style.backgroundColor = 'blue'; // 单个属性修改

div.style.setProperty('color', 'white', 'important'); // 带优先级修改

// 添加/删除类

div.classList.add('active'); // 添加类

div.classList.remove('inactive'); // 移除类

2. 常用事件绑定

div.addEventListener('click', () => {

alert('Div被点击!');

});

div.onclick = function() {

console.log('传统事件绑定');

};

三、Div 布局技术速查

1. 流动布局(默认)

/* 常规流布局 */

.container {

width: 90%;

max-width: 1200px;

margin: 0 auto;

}

2. 现代布局方案

Flexbox 布局

/* 水平居中 */

.flex-container {

display: flex;

justify-content: center;

}

/* 垂直居中 */

.flex-container {

display: flex;

align-items: center;

min-height: 100vh;

}

Grid 布局

/* 网格布局 */

.grid-container {

display: grid;

grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

gap: 20px;

}

3. 传统定位方案

/* 绝对定位 */

.positioned-div {

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

}

/* 固定定位 */

.fixed-header {

position: fixed;

top: 0;

width: 100%;

z-index: 999;

}

四、高频布局技巧

清除浮动

.clearfix::after {

content: "";

display: table;

clear: both;

}

视觉隐藏内容

.visually-hidden {

position: absolute;

width: 1px;

height: 1px;

padding: 0;

margin: -1px;

overflow: hidden;

clip: rect(0, 0, 0, 0);

white-space: nowrap;

border: 0;

}

响应式断点

@media (max-width: 768px) {

.container {

width: 100%;

}

}

五、避坑指南

不要滥用!important

优先级过高的样式难以维护 合理使用overflow.scroll-box {

overflow: auto; /* 内容溢出时滚动 */

max-height: 300px;

}

盒模型理解/* 总宽度计算公式:width + padding + border + margin */

.box {

width: 200px;

padding: 20px;

border: 1px solid #000;

margin: 10px;

box-sizing: border-box; /* 包含padding和border */

}

📌 最佳实践建议:

使用语义化标签替代div(如

)布局优先选择Flexbox/Grid避免使用float布局除非必要通过CSS Reset统一浏览器默认样式

📚 推荐阅读

wx群聊AI总结助手历时两周半开发的一款加载live2模型的浏览器插件github优秀开源作品集