微调 跟随父盒子大小自适应宽高 两栏布局

it2026-10-03  3

微调 跟随父盒子大小自适应宽高 两栏布局

1.微调

我们可以利用 定位将没有对齐的元素进行微调来对齐

情况一:

<h3>1. 用于对齐方式的微调</h3> <div class="input-item"> <input type="checkbox"> <span>记住密码</span> </div> body { padding: 0 40px; font-size: 14px; } .input-item{ border: 1px solid #000; } .input-item input{ /* 相对定位:相对于自己原来的位置 */ position: relative; top: 2px; }

情况二:

<h3>2. 导航状态</h3> <div class="navs"> <a href="#">首页</a> <a href="#">新闻</a> <a href="#">杂志</a> </div> /* 导航 */ .navs{ border: 1px solid #000; width: 220px; height: 30px; } .navs a{ text-decoration: none; color: #333; font-size: 18px; display: block; width: 70px; height: 29px; line-height: 29px; text-align: center; /* border: 1px solid #000; */ /* 通过浮动来成行显示 */ float: left; position: relative; bottom: -2px; } .navs a:hover{ border-bottom: 2px solid red; }

2. 跟随父盒子大小自适应宽高

问题: 如果子元素想根据父元素的宽高来自适应调整自己的宽高 方案: 使用绝对定位,同时设置 left 和 right,top 和 bottom,可实现相对父元素的自适应布局。一个重要的前提是不要为盒子指定 width 或 height

<h4>相对定位</h4> <div class="box"> <div class="inner"></div> </div> body { padding: 0 10px; } .box { width: 300px; height: 200px; background-color: #0094ff; position: relative; } .inner{ background-color: darkred; /* 绝对定位:相对于 最近的 有定位的 祖元素 */ position: absolute; top: 40px; bottom: 40px; left:20px; right: 20px; }

3. 两栏布局

<!-- 侧边栏 --> <div class="aside"></div> <!-- 内容区 --> <div class="main"></div> body { margin: 0px; color: #333; line-height: 1.5em; } .aside { width: 180px; /* height: 100%; */ background-color: #0094ff; border: 1px solid #000; /* 使用固定定位 让侧边栏靠左不动,会脱离标准文档流,所以 当前元素的高度 会以 窗口高度为参照 */ position: fixed; left: 0px; top: 0px; bottom: 0px; } .main { margin-left: 200px; }
最新回复(0)