简体   繁体   中英

Why doesn't my div align properly with background img?

A short question from a newbie designer... Say I have a <div class="red"> folowed by a <div class="filler"> . If I use margin-left:10% on the first div and I use a background image on the second div (height=1px and width=300px) and I repeat it vertically and start it left: 10% , they won't align... Why not?

HTML:

<!doctype html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
  <div class="test">
  </div>
  <div class="filler">
  </div>
</body>
</html> 

CSS:

html, body {
   height: 100%;
}
.test{

  background-color: red;
  width: 300px;
  height: 300px;
  margin-left: 10%;
}
.filler{
  width:100%;
  height: 300px;
  background: url(../img/test.jpg) top left 10% repeat-y;
}

Maybe I'm missing something, but what? Thanks a lot!

In the case of background images, using a percentage as a position has a special meaning.

It does not (as you might expect) align the left edge of the image at the percentage you give, but rather it aligns the percentage with the percentage.

Okay, that makes no sense in words!

Basically, it's like this:

0%:
[IMAGE        ]
50%:
[    IMAGE    ]
100%:
[        IMAGE]

Does that make more sense? The best way to fix this is to just add the margin-left:10% to the .filler instead of positioning the background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM