网站首页 > 知识剖析 正文
前端面试题中经常会出现这个问题,接下来,小郭就带你揭秘几种最常见的答案。
先设定一个html结构以及css的基本样式。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>如何让div实现水平居中</title> </head> <body> <div id="dad"> <div id="son"></div> </div> </body> </html>
css样式
#dad{ width: 400px; height: 200px; border: 3px solid green; margin: 30px auto; } #son{ width: 100px; height: 100px; background: purple; }
方法一:纯margin
/*css处添加下面代码*/ #son{ margin:0 auto; }
方法二:position定位
/*css处添加下面代码*/ #dad{ position: relative; } #son{ position: absolute; left:50%; margin-left:-50px; } /*注意:margin-left是负值,是#son这个div宽的一半*/?
方法三:flexbox
/*css处添加下面代码*/ #dad{ display: flex; justify-content: center; } /*注意:弹性盒子的大部分属性都是写在父级上的*/
以上三种是最常见的,下期我们来讲讲其他奇形怪状的方法~
关注我,带你了解更多前端干货!
学前端,就选锐盈课堂!
猜你喜欢
- 2024-11-12 原来隐藏一个DOM元素可以有这么多种方式,最后一种你肯定不知道
- 2024-11-12 你知道什么是BFC么 你知道什么是bfc么英语
- 2024-11-12 为什么我写的z-index不生效? z index无效
- 2024-11-12 开发人员在编写 HTML 和 CSS 时最常犯的六大错误
- 2024-11-12 CSS 12个趣味小技巧大公开 | 原力计划
- 2024-11-12 谈谈工作中常用的设计模式 工作设计模型
- 2024-11-12 CSS 父元素中的绝对定位 父元素设置相对定位
- 2024-11-12 菜鸟学习记:第二十五天 菜鸟学习记
- 2024-11-12 响应式网页中的高度设计,你认真的吗?
- 2024-11-12 前端基础CSS为什么要用定位?定位的4中分类是什么?
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)