[CSS] 图片九宫格

效果

[CSS] 图片九宫格_第1张图片

index.html

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
    <title> Document title>
    <link type="text/css" rel="styleSheet" href="index.css" />
  head>
  <body>
    <div class="img-container">
      
      <div class="img-item">div>
      <div class="img-item">div>
      <div class="img-item">div>
      <div class="img-item">div>
      <div class="img-item">div>
      <div class="img-item">div>
      <div class="img-item">div>
      <div class="img-item">div>
      <div class="img-item">div>
    div>
  body>
html>

index.css

body{
  width: 500px;
  height: 500px;
  margin: 0 auto;
  margin-top: 120px;
  /*设置item元素布局为网关布局*/
  display: flex;
  justify-content: center;
  align-items: start;
  background-color: #171717;
  padding-top: 100px;
}

.img-container{
  width: 300px;
  height: 300px;
  /*网格布局*/ 
  display: grid;
  /*网格布局列数与宽度*/ 
  grid-template-columns: repeat(3,1fr);
  /*网格布局行数与高度*/ 
  grid-template-rows: repeat(3,1fr);
}

.img-item {
  /*添加阴影效果*/ 
  box-shadow: inset 0 0 0 1px #fff;
  /*元素属性变化时平滑过度,优化视觉体验*/ 
  transition: 0.5s;
  background-size: 300px 300px;
  /*设置背景图像*/ 
  background-image: url(./1.png);
  /*相对定位*/ 
  position: relative;
}

/* 3n+1  选中第一列的元素 1 4 7*/ 
.img-item:nth-child(3n+1){
  background-position-x: 0;
  left: -20px;
}

/* 3n+2  选中第二列的元素 2 5 8*/ 
.img-item:nth-child(3n + 2){
  background-position-x: -100%;
  left: 0;
}

/* 3n+0  选中第三列的元素 3 6 9*/ 
.img-item:nth-child(3n){
  background-position-x: -200%;
  left: 20px;
}

/* n+7  选中第三行的元素 7 8 9*/ 
.img-item:nth-child(n + 7){
  background-position-y: -200%;
  top: 20px;
}

/* -n + 6 选中第一、二行的元素 6 5 4 3 2 1*/ 
.img-item:nth-child(-n + 6){
  background-position-y: -100%;
  top: 0px;
}
/* -n + 6 选中第一行的元素 3 2 1*/ 
.img-item:nth-child(-n+3){
  background-position-y: 0;
  top: -20px;
}

/* 鼠标移入时修改 img-item 属性值 */ 
.img-container:hover .img-item {
  left: 0;
  top: 0;
  /*隐藏的阴影效果*/
  box-shadow: inset 0 0 0 0px #fff;
}

1.png

[CSS] 图片九宫格_第2张图片

你可能感兴趣的:(语言-HTML,css,前端,nth-child,box-shadow)