<style>
/* 父元素 */
.bigBox{
width: 800px;
height: 600px;
border: 1px solid #000;
}
/* 子元素 */
.smallBox{
width: 300px;
height: 200px;
border: 1px solid red;
}
/* 方法1 position定位 */
.bigBox1{
position: relative;
}
.smallBox1{
position: absolute;
left: 50%;
margin-left: -150px;
top: 50%;
margin-top: -100px;
text-align: left;
}
/* 方法2 css3 flex方法 */
.bigBox2{
display: flex;
}
.smallBox2{
text-align: center;
margin: auto;
}
/* 方法3 css3display方法,box-pack和box-align是关键 */
.bigBox3{
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Chrome, and Opera */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
}
.smallBox3{
text-align: right;
}
/* 方法4 与方法1类似,用了css3的calc计算,符号左右为空格 */
.bigBox4{
position: relative;
}
.smallBox4{
position: absolute;
left: calc(50% - 150px);
top: calc(50% - 100px);
}
/* 方法5 */
.smallBox5{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="bigBox bigBox1"> <!-- 以下五种方法都可以实现div完美居中 -->
<!-- <div class="smallBox smallBox1">small1</div>
<div class="smallBox smallBox2">small2</div>
<div class="smallBox smallBox3">small3</div> -->
<div class="smallBox smallBox4"></div>
<div class="smallBox smallBox5"></div>
</div>
实际使用中人们可以按照实际情况使用不同的方法来实现居中。
例如:margin和padding的%也可以实现效果。
写出来只为记录和学习。
div居中是前端面试比较常问的问题,不过在我看来是一些幼稚前端的自娱自乐罢了,实际开发中使用的场景并不是很多。
(也是有些面试的人真的把各种各样div居中当成css熟练程度的标准)
css居中的方法(自用、误杠)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 最近写网页经常需要将div在屏幕中居中显示,遂记录下几个常用的方法,都比较简单。 水平居中直接加上 标签即可,或者...
- 方法一 CSS代码 HTML代码 方法二 CSS代码 HTML代码 第一种方法代码看起来虽多,但有时比第二种方法好...