1 Img居中
Img居中需要设置父div的line-height和text-align:center属性,也需要设置img的vertical-align:middle属性。
2 Div居中
div居中需要设置父div的display: flex属性,还需要设置子div(居中的div)的margin: auto;属性。
3 源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>居中</title>
</head>
<style type="text/css">
body{
width: 100%;
}
.middle{
width: 100%;
height: 600px;
}
.my_title{
width: 100%;
font-size: 18px;
}
/* -- 1 图片居中 -- */
/* 主要图片不需要做任何处理,父div设置好即可 */
.my_img{
/* 高度不能决定 垂直居中 */
height: 500px;
/* 宽度决定 水平居中 */
width: 60%;
/* text-align决定水平居中 */
text-align: center;
/* 行高决定 垂直居中 */
line-height: 500px;
background-color: blue;
}
.my_img_center{
width: 400px;
height: 200px;
/* 决定垂直居中 */
vertical-align: middle;
}
/* -- 2 Div居中 -- */
.my_div{
/* 宽度决定 水平居中 */
width: 60%;
/* 高度不能决定 垂直居中 */
height: 500px;
/* 决定div居中,如果水平居中可不要 */
display: flex;
background-color: blue;
}
.my_div_center{
width: 200px;
height: 200px;
background-color: red;
/* div水平和垂直居中 */
margin: auto;
/* div水平居中 */
/* margin: 0 auto; */
/* div垂直居中 */
/* margin: auto 0; */
}
/*-- 3 文字垂直居中 -- */
.my_text_title{
width:100%;
height: 200px;
/* 控制垂直居中 */
display: table;
}
.my_text_title>div{
font-size: 18px;
/* 控制水平居中 */
text-align: center;
vertical-align: middle;
/* 控制垂直居中 */
display: table-cell;
}
</style>
<body>
<div class="middle">
<div class="my_title">图片居中</div>
<div class="my_img">
<img class="my_img_center" src="img/my_img.jpg" />
</div>
</div>
<div class="middle">
<div class="my_title">Div居中</div>
<div class="my_div">
<div class="my_div_center">Div</div>
</div>
</div>
<div class="middle">
<div class="my_title">文字居中</div>
</div class="my_text_title">
<div>河南大学我爱你</div>
<div>
</div>
</body>
</html>
本文详细介绍了网页中图片和div的居中布局方法,包括设置父元素的line-height、text-align和display属性,以及子元素的vertical-align和margin属性。通过实例代码展示了如何实现图片和div的水平及垂直居中,帮助开发者更好地掌握网页布局技巧。
297

被折叠的 条评论
为什么被折叠?



