css background-position属性

定义

background-position 属性用于设置或获取元素背景图像相对于原点的初始位置。

background-position 基本语法

background-position:背景图片水平位置参数 背景图片垂直位置参数 ;

background-position 通常使用水平方向以及垂直方向的组合来定义背景图片呈现的位置。

属性值

在这里插入图片描述

可以通过分别设置 background-position-xbackground-position-y 来设置「靠左与靠上的距离」,如下:

<!DOCTYPE html>
<html>
<head>
<style>
   .container{
   	  width: 600px;
   	  height: 500px;
   	  background-color: #ddd;
   	  border: 1px solid #333;
   	  border-radius: 10px;
      background-image:url("cat.jpg");
      background-repeat:no-repeat;
      background-position-x:30px;
      background-position-y:0;
   }
</style>
<script>
</script>
</head>
<body>
<div class="container"></div>
</body>
</html>

页面效果:
在这里插入图片描述

对齐方式

background-position:right bottom; // 靠右靠下对齐

background-position:30px 60px; //靠左 30px 靠上 60 px 的位置

background-position:10% 50%; // 靠左 10% 靠上 50% 的位置

background-position:10%; // 效果同上一行,靠左 10% 靠上 50% 的位置

水平垂直居中

设置图片水平垂直居中,如下:

<!DOCTYPE html>
<html>
<head>
<style>
   .container{
   	  width: 600px;
   	  height: 500px;
   	  background-color: #ddd;
   	  border: 1px solid #333;
   	  border-radius: 10px;
      background-image:url("cat.jpg"); //背景的图片路径或网址
      background-repeat:no-repeat; //背景图片不要重覆显示(仅显示一次)
      background-position:50% 50%;
   }
</style>
<script>
</script>
</head>
<body>
<div class="container"></div>
</body>
</html>

页面效果:
在这里插入图片描述

background-repeat 属性

background-repeat 属性定义了图像的平铺模式,用于设置是否及如何重复背景图像。

基本语法:

background-repeat:repeat|repeat-x|repeat-y|no-repeat;

  • repeat:默认值,背景图像将向垂直和水平方向重复。

  • repeat-x:只有水平位置会重复背景图像。

  • repeat-y:只有垂直位置会重复背景图像。

  • no-repeat:设置背景图片不会重复。

包含多张背景图片

还可以实现一个包含多个背景图像的框,如下:

<!DOCTYPE html>
<html>
<head>
<style>
   .container{
   	  width: 600px;
   	  height: 600px;
   	  background-color: #eee;
   	  border: 1px solid #333;
   	  border-radius: 10px;
      background-position: 
      top 0 left 0,
      top 0 right 0,
      bottom 20px left 80px,
      bottom 90px right 10px;
      background-image:url("78x78.png"),url("500x375.jpg"),url("300-300.jpeg"),url("350x350.png");
      background-repeat:no-repeat;
      background-size: 200px 200px;
   }
</style>
<script>
</script>
</head>
<body>
<div class="container"></div>
</body>
</html>

页面效果:
在这里插入图片描述

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>