background-position百分比原理_html/css_WEB-ITnose

WBOY
풀어 주다: 2016-06-24 11:42:03
원래의
1151명이 탐색했습니다.

今天帮别人调代码时,看到一个样式:

background-position: 50% 0;background-size: 100% auto;
로그인 후 복사

对background-size:100% auto,意思是背景图片宽度为元素宽度*100%,高度等比缩放。详情可见css3 background。

对background-position很自然的以为百分比是根据父元素宽度计算的,但background-position真的不是,它有一套自己的原理。下面详细介绍。

一、等价写法

在看各类教程时有以下等价写法:

  • top left, left top 等价于 0% 0%.
  • top, top center, center top 等价于 50% 0%.
  • right top, top right 等价于 100% 0%.
  • left, left center, center left 等价于 0% 50%.
  • center, center center 等价于 50% 50%.
  • right, right center, center right 等价于 100% 50%.
  • bottom left, left bottom 等价于 0% 100%.
  • bottom, bottom center, center bottom 等价于 50% 100%.
  • bottom right, right bottom 等价于 100% 100%.
  • 那么为什么left,top就等价于0% 0%,right bottom等价于100% 100%呢?

    二、background-position百分比计算公式

    background-postion:x y;x:{容器(container)的宽度?背景图片的宽度}*x百分比,超出的部分隐藏。y:{容器(container)的高度?背景图片的高度}*y百分比,超出的部分隐藏。
    로그인 후 복사

    有了这个公式,就很容易理解百分百写法了,推算一下也就很容易理解上面各类等价写法了。

    三、举例

    1、background-position:center center等价于background-position:50% 50%等价于background-position:?px ?px

    例子中用到背景图如下【尺寸:200px*200px】:

    背景图在容器中居中。

    <style type="text/css">.wrap{    width: 300px;    height: 300px;    border:1px solid green;    background-image: url(img/image.png);    background-repeat: no-repeat;/*    background-position: 50% 50%;*/    background-position: center center;}</style><div class="wrap"></div>
    로그인 후 복사

    效果都是让背景图片居中

    如上通过设置百分比和关键字能实现背景图居中,如果要实现通过具体值来设置图片居中该设置多少?

    根据上面公式:

    x=(容器的宽度-背景图宽度)*x百分比=(300px-200px)*50%=50px;

    y=(容器的高度-背景图高度)*y百分比=(300px-200px)*50%=50px;

    即设置background-postion:50px 50px;

    测试一下:

    <style type="text/css">.wrap{    width: 300px;    height: 300px;    border:1px solid green;    background-image: url(img/image.png);    background-repeat: no-repeat;/*    background-position: 50% 50%;*//*    background-position: center center;*/    background-position: 50px 50px;}</style><div class="wrap"></div>
    로그인 후 복사

    效果同样居中。

    원천:php.cn
    본 웹사이트의 성명
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
    최신 이슈
    인기 튜토리얼
    더>
    최신 다운로드
    더>
    웹 효과
    웹사이트 소스 코드
    웹사이트 자료
    프론트엔드 템플릿
    회사 소개 부인 성명 Sitemap
    PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!