网页中如何用HTMLCSS实现图片居中于页面

html-css09

网页中如何用HTMLCSS实现图片居中于页面,第1张

图片是一个块级元素,可以用块级元素的方法居中,居中的方法有很多,我随便列举几个:

一:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>居中</title>

</head>

<style type="text/css">

.one{

width:500px

height:500px

margin: 0 auto

background: orange

position: relative

}

.two{

width: 200px

height: 200px

background: orangered

/*居中开始*/

position: absolute

top: 50%

left: 50%

transform: translate(-50%,-50%)

}

</style>

<body>

<div class="one">

<div class="two"></div>

</div>

</body>

</html>

二:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>居中</title>

</head>

<style type="text/css">

.one{

width: 500px

height: 500px

background: blue

margin: 0 auto

position: relative

}

.two{

width: 200px

height: 200px

background: lightblue

position: absolute

top: 0right: 0bottom: 0left: 0margin: auto

}

</style>

<body>

<div class="one">

<div class="two">

</div>

</div>

</body>

</html>

三:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>居中</title>

</head>

<style type="text/css">

.one{

width: 500px

height: 500px

margin: 0 auto

background: green

position: relative

}

.two{

width: 200px

height: 100px

background: greenyellow

position: absolute

top: 50%

left: 50%

margin-top: -50px

margin-left: -100px

}

</style>

<body>

<div class="one">

<div class="two">

</div>

</div>

</body>

</html>

第一步:我们需要准备一个图像

作为一个例子,我想在深色背景的背景上放置白色文字。

第二步:将图像和字母放在一个div元素中

将图像和字母放在一个div标签中。在示例中,将文字“万里长城”放在p标记中。当然您可以使用标题标签而不是p标签,也可以使用span标签。

1

2

3

4

<div class = "example" >

<img src="image/greatwall.jpg">

<p>万里长城</p>

</div>

第三步:指定position属性

为每个元素设置css的position属性。

对作为父元素的div指定为position:relative,以及对包含该字符串的p标签设置为absolute。img标签不动。

把p标签的位置设置为top:0left:0。

为了把图像放在横向上,请指定为img标签的宽度为width : 100%。

1

2

3

4

5

6

7

8

9

10

11

12

.example{/*父元素div*/

position: relative/*相対定位*/

}

.example p {

position: absolute/*绝対定位*/

color: white/*文字设为白色*/

top: 0

left: 0

}

.example img {

width: 100%

}

你的html中只要有匹配这个选择器的dom结构就会自动出现有这个图片的。不过你这个css选择器太复杂了,需要类似下面这个结构才能匹配(为了简便,这里都是用的div标签,实际情况可能会很复杂):

<div class="public_nav_v3">

<div class="info_wrap">

<div class="info">

<div class="right">

<div class="login_box">

<div class="r_pic">

<div class="avatar_wrap">

<div class="frame frame_1">

......在最里面的这个div里就会出现那个图片了,当然这里很可能还要设定width、height等属性才行,总之就是这么个意思......

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>