目 录CONTENT

文章目录
es6

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

Administrator
2025-02-28 / 0 评论 / 0 点赞 / 20 阅读 / 0 字

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

一、Div 核心属性

1. HTML 属性

属性 说明 示例
id 唯一标识符 <div id="main">
class 类名(用于CSS选择器) <div class="box">
style 内联样式 <div style="color:red">
title 鼠标悬停提示文本 <div title="提示">

2. CSS 核心属性

属性 说明 值类型 示例
display 显示模式 block/inline/flex display: flex;
position 定位方式 static/relative/absolute/fixed position: relative;
width 宽度 px/%/auto width: 100%;
height 高度 px/%/auto height: auto;
margin 外边距 px/auto margin: 20px;
padding 内边距 px/auto padding: 10px;
box-sizing 盒子模型 border-box/content-box box-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;
}

四、高频布局技巧

  1. 清除浮动
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
  1. 视觉隐藏内容
.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;
}
  1. 响应式断点
@media (max-width: 768px) {
  .container {
    width: 100%;
  }
}

五、避坑指南

  1. 不要滥用!important
    • 优先级过高的样式难以维护
  2. 合理使用overflow
    .scroll-box {
      overflow: auto; /* 内容溢出时滚动 */
      max-height: 300px;
    }
    
  3. 盒模型理解
    /* 总宽度计算公式:width + padding + border + margin */
    .box {
      width: 200px;
      padding: 20px;
      border: 1px solid #000;
      margin: 10px;
      box-sizing: border-box; /* 包含padding和border */
    }
    

📌 最佳实践建议

  • 使用语义化标签替代div(如<section><article>
  • 布局优先选择Flexbox/Grid
  • 避免使用float布局除非必要
  • 通过CSS Reset统一浏览器默认样式

📚 推荐阅读

0
es6
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区