顯示具有 CSS 標籤的文章。 顯示所有文章
顯示具有 CSS 標籤的文章。 顯示所有文章
2022-07-15 12:38

[轉載] CSS 变量教程

轉載自:阮一峰 CSS 变量教程

今年三月,微软宣布 Edge 浏览器将支持 CSS 变量。

这个重要的 CSS 新功能,所有主要浏览器已经都支持了。本文全面介绍如何使用它,你会发现原生 CSS 从此变得异常强大。

一、变量的声明

声明变量的时候,变量名前面要加两根连词线(--)。

body {
  --foo: #7F583F;
  --bar: #F7EFD2;
}

上面代码中,body选择器里面声明了两个变量:--foo--bar

它们与colorfont-size等正式属性没有什么不同,只是没有默认含义。所以 CSS 变量(CSS variable)又叫做"CSS 自定义属性"(CSS custom properties)。因为变量与自定义的 CSS 属性其实是一回事。

你可能会问,为什么选择两根连词线(--)表示变量?因为$foo被 Sass 用掉了,@foo被 Less 用掉了。为了不产生冲突,官方的 CSS 变量就改用两根连词线了。

各种值都可以放入 CSS 变量。

:root{
  --main-color: #4d4e53;
  --main-bg: rgb(255, 255, 255);
  --logo-border-color: rebeccapurple;

  --header-height: 68px;
  --content-padding: 10px 20px;

  --base-line-height: 1.428571429;
  --transition-duration: .35s;
  --external-link: "external link";
  --margin-top: calc(2vh + 20px);
}

变量名大小写敏感,--header-color--Header-Color是两个不同变量。

二、var() 函数

var()函数用于读取变量。

a {
  color: var(--foo);
  text-decoration-color: var(--bar);
}

var()函数还可以使用第二个参数,表示变量的默认值。如果该变量不存在,就会使用这个默认值。

color: var(--foo, #7F583F);

第二个参数不处理内部的逗号或空格,都视作参数的一部分。

var(--font-stack, "Roboto", "Helvetica");
var(--pad, 10px 15px 20px);

var()函数还可以用在变量的声明。

:root {
  --primary-color: red;
  --logo-text: var(--primary-color);
}

注意,变量值只能用作属性值,不能用作属性名。

.foo {
  --side: margin-top;
  /* 无效 */
  var(--side): 20px;
}

上面代码中,变量--side用作属性名,这是无效的。

三、变量值的类型

如果变量值是一个字符串,可以与其他字符串拼接。

--bar: 'hello';
--foo: var(--bar)' world';

利用这一点,可以 debug(例子)。

body:after {
  content: '--screen-category : 'var(--screen-category);
}

如果变量值是数值,不能与数值单位直接连用。

.foo {
  --gap: 20;
  /* 无效 */
  margin-top: var(--gap)px;
}

上面代码中,数值与单位直接写在一起,这是无效的。必须使用calc()函数,将它们连接。

.foo {
  --gap: 20;
  margin-top: calc(var(--gap) * 1px);
}

如果变量值带有单位,就不能写成字符串。

/* 无效 */
.foo {
  --foo: '20px';
  font-size: var(--foo);
}

/* 有效 */
.foo {
  --foo: 20px;
  font-size: var(--foo);
}

四、作用域

同一个 CSS 变量,可以在多个选择器内声明。读取的时候,优先级最高的声明生效。这与 CSS 的"层叠"(cascade)规则是一致的。

下面是一个例子

<style>
  :root { --color: blue; }
  div { --color: green; }
  #alert { --color: red; }
  * { color: var(--color); }
</style>

<p>蓝色</p>
<div>绿色</div>
<div id="alert">红色</div>

上面代码中,三个选择器都声明了--color变量。不同元素读取这个变量的时候,会采用优先级最高的规则,因此三段文字的颜色是不一样的。

这就是说,变量的作用域就是它所在的选择器的有效范围。

body {
  --foo: #7F583F;
}

.content {
  --bar: #F7EFD2;
}

上面代码中,变量--foo的作用域是body选择器的生效范围,--bar的作用域是.content选择器的生效范围。

由于这个原因,全局的变量通常放在根元素:root里面,确保任何选择器都可以读取它们。

:root {
  --main-color: #06c;
}

五、响应式布局

CSS 是动态的,页面的任何变化,都会导致采用的规则变化。

利用这个特点,可以在响应式布局的media命令里面声明变量,使得不同的屏幕宽度有不同的变量值。

body {
  --primary: #7F583F;
  --secondary: #F7EFD2;
}

a {
  color: var(--primary);
  text-decoration-color: var(--secondary);
}

@media screen and (min-width: 768px) {
  body {
    --primary:  #F7EFD2;
    --secondary: #7F583F;
  }
}

六、兼容性处理

对于不支持 CSS 变量的浏览器,可以采用下面的写法。

a {
  color: #7F583F;
  color: var(--primary);
}

也可以使用@support命令进行检测。

@supports ( (--a: 0)) {
  /* supported */
}

@supports ( not (--a: 0)) {
  /* not supported */
}

七、JavaScript 操作

JavaScript 也可以检测浏览器是否支持 CSS 变量。

const isSupported =
  window.CSS &&
  window.CSS.supports &&
  window.CSS.supports('--a', 0);

if (isSupported) {
  /* supported */
} else {
  /* not supported */
}

JavaScript 操作 CSS 变量的写法如下。

// 设置变量
document.body.style.setProperty('--primary', '#7F583F');

// 读取变量
document.body.style.getPropertyValue('--primary').trim();
// '#7F583F'

// 删除变量
document.body.style.removeProperty('--primary');

这意味着,JavaScript 可以将任意值存入样式表。下面是一个监听事件的例子,事件信息被存入 CSS 变量。

const docStyle = document.documentElement.style;

document.addEventListener('mousemove', (e) => {
  docStyle.setProperty('--mouse-x', e.clientX);
  docStyle.setProperty('--mouse-y', e.clientY);
});

那些对 CSS 无用的信息,也可以放入 CSS 变量。

--foo: if(x > 5) this.width = 10;

上面代码中,--foo的值在 CSS 里面是无效语句,但是可以被 JavaScript 读取。这意味着,可以把样式设置写在 CSS 变量中,让 JavaScript 读取。

所以,CSS 变量提供了 JavaScript 与 CSS 通信的一种途径。

八、参考链接

2014-03-05 15:18

CSS 選擇器權重表

!important style="" #id htmlTag .class
權重 10000 1000 100 10 1

Ex:
.title {} /* 1 */

div span.title {} /* 21 */

#product-list .title {} /* 101 */

2014-02-21 17:43

[T4] url, base64, sprite 三種格式的 icons.css 產生器

之前有寫過 [PHP] url, base64, sprite 三種格式的 icons.css 產生器,這次換用 C# T4 Text Templates 來製作這個功能:

int spriteGap = 30;  
var scanTypes = new string[]{".jpg", ".gif", ".png"};

string workDirectory = 
    Path.GetDirectoryName(this.Host.TemplateFile);


/* 取得圖檔資訊 */  
List<ImageInfo> imageList = Directory
    .EnumerateFiles(Path.Combine(workDirectory, "icons"))
    .Where(path => scanTypes.Contains(Path.GetExtension(path)))
    .Select(path => 
    {
        var image = Image.FromFile(path);

        return new ImageInfo{
            FilePath = path,
            FileName = Path.GetFileName(path),
            IconImage = image,
            IconName = Path.GetFileNameWithoutExtension(path),
            TopOffset = 0,
            Width = image.Width,
            Height = image.Height,
            IsAnimated = ImageAnimator.CanAnimate(image),
        };
    })
    .OrderBy(info => info.IsAnimated)
    .ToList();



/*檢查重複的圖檔名稱*/
List<string> repeatList = imageList.GroupBy(info => info.IconName)
    .Where(g => g.Count() > 1)
    .SelectMany(g => g.Select(x => x.FileName))
    .ToList();

if(repeatList.Count > 0){
    throw new Exception(
        "出現重複的圖檔名稱[" + String.Join(", ", repeatList) + "]"
    );
}   



/* 製作 CSS Sprite */
int sumHeight = imageList.Sum( info => info.Height);
int spriteWidth = imageList.Max( info => info.Width);
int spriteHeight = sumHeight + (imageList.Count - 1) * spriteGap;

var bitmap = new Bitmap(spriteWidth, spriteHeight);

using (Graphics graphics = Graphics.FromImage(bitmap))
{           
    int nextTop = 0;
    for(int i=0; i< imageList.Count; i++){
        /*忽略具有動畫的 GIF 圖片*/ 
        if(imageList[i].IsAnimated){ continue; } 

        imageList[i].TopOffset = nextTop;
        
        graphics.DrawImage(imageList[i].IconImage, 0, nextTop);
            
        nextTop = nextTop + imageList[i].Height + spriteGap;
    }
        
    graphics.Save();
}

SaveOutput("icons.sprite.png"); 
bitmap.Save(
    Path.Combine(workDirectory, "icons.sprite.png"), 
    ImageFormat.Png
);
bitmap.Dispose();

下載完整程式: t4_make_icons_css.zip
2014-02-05 20:25

[CSS] float 與 clear

float

一開始是用來定義文繞圖的呈現,後來其浮動特性很適合用來排版佈局,所以大部分的網頁都用這種方式排版。

特性:
  • 不佔用父元素的空間
  • 寬高會內縮至子元素所呈現的大小
  • 會排擠其他相鄰的 inline 元素
  • 在所定位的空間不足時會自動換行

<div style="border:1px solid #f00; float:left;">div 1</div>
<div style="background:#0f0;">div 2</div>
div1
div2

透過上面的範例可以看出因為 div1 不佔用空間而讓 div2 的位子上移了,然而呈現與 div1 重疊的效果,以及可以看到 float 排擠文字的特性,而讓 div2 的文字被擠到 div1 之後。



clear

清除在元素相鄰邊上的 float 元素

屬性:
  • none 不做任何 clear 動作
  • left 將元素向下換行,來排除具有 float:left 的相鄰元素
  • right 將元素向下換行,來排除具有 float:right 的相鄰元素
  • both 將元素向下換行,來排除具有 float:left 或 float:right 的相鄰元素

<div style="border:1px solid #f00; float:left;">div1</div>
<div style="background:#0f0; clear:left;">div2</div>
div1
div2

這個範例在 div2 加上 clear:left 的屬性,讓 div2 根據前一個具有 float:left 元素之後向下換行,來排除具有 float:left 的相鄰元素。


<div style="border:1px solid #f00; float:left;">div1</div>
<div style="background:#0f0; clear:right;">div2</div>
div1
div2

這個範例則是將 div2 換成 clear:right,可以看到 div1 與 div2 仍舊重疊在一起,這是因為 div2 前一個具有 float:right 不存在,而 div1 的 float:left 不是 div2 clear:right 排除的對象。
2014-01-30 20:46

[CSS] display inline, block 與 inline-block

inline 行內 (例如: <b>,<span>),具有以下特性:
  • 會連接在文字及 inline 元素之後
  • 不具有 width, height 以及上下的 padding, margin (padding-top, padding-bottom, margin-top, margin-bottom)
  • 寬度、高度會內縮至所含文字所使用的空間

block 區塊 (例如: <p>,<div>),具有以下特性:
  • 會獨佔父元素一整行的空間
  • 具有完整 width, height 及 padding, margin 屬性
  • 當不指定寬度時,預設寬度會擴張至一整列
  • 當不指定高度時,預設高度會內縮至子元素所使用的空間

inline-block 行內-區塊 (例如: <img>,<button>),同時具備 inline 與 block 的特性:
  • 會連接在文字及 inline 元素之後
  • 具有完整 width, height 及 padding, margin 屬性
  • 當不指定寬度、高度時,預設會內縮至所含文字所使用的空間
2014-01-30 20:41

[CSS] Selector Meaning

SelectorMeaning
ABA and B
A, BA or B
A Bforeach B whose parents contains A
A > Bforeach B whose parent is A
A + Bforeach B whose previous sibling is A
A ~ Bforeach B whose previous siblings contains A
2014-01-21 00:23

[Less] 簡單做到背景漸層

對選顏色不擅長,又想在網頁做出 CSS 漸層效果,Less 提供了兩個方便的函數 lighten(加亮顏色)、darken(加深顏色),透過這兩個函數就可以輕鬆產生漸層所需要的色差,然後調整百比值就可以控制漸層的色階。

.toolbar {
    @color: #914;
    @lighten: lighten(@color, 3%);
    @darken: darken(@color, 3%);

    background-color: @color;
    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@lighten), to(@darken));
    background-image: -webkit-linear-gradient(top, @lighten, @darken);
    background-image: -moz-linear-gradient(top, @lighten, @darken);
    background-image: -ms-linear-gradient(top, @lighten, @darken);
    background-image: -o-linear-gradient(top, @lighten, @darken);
    background-image: linear-gradient(to bottom, @lighten, @darken);
}

上面除了用 linear-gradient 來產生漸層,額外還加上了 background-color 這個保險,讓不支援 CSS3 的 browser 也能有基本的底色。


這樣寫還是有點麻煩,如果包成 mixin 會更方便,如下:
.bg-vertical-gradient(@color, @amount:3%) {
    @lighten: lighten(@color, @amount);
    @darken: darken(@color, @amount);

    background-color: @color;
    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@lighten), to(@darken));
    background-image: -webkit-linear-gradient(top, @lighten, @darken);
    background-image: -moz-linear-gradient(top, @lighten, @darken);
    background-image: -ms-linear-gradient(top, @lighten, @darken);
    background-image: -o-linear-gradient(top, @lighten, @darken);
    background-image: linear-gradient(to bottom, @lighten, @darken);
}

.toolbar {
    .bg-vertical-gradient(#914);
}

.banner {
    .bg-vertical-gradient(#702, 5%);
}
2013-08-17 14:55

[PHP] url, base64, sprite 三種格式的 icons.css 產生器

先做一個假設,如果 icon 的檔名就是 css 的 class 樣式名稱,那麼我們只要掃瞄資料夾的 Icon 圖檔,然後產生對應的 CSS 檔案,這樣就可以省去製作 Sprite 圖檔跟維護 CSS 對應的問題。

第一種 url 格式只是取得路徑的問題。

第二種 base64 格式可以透過 base64_encode(file_get_contents($path)); 就簡單的達成。

第三種 sprite 格式則使用 Imagick 去處理,會比較快樂。


接著以下就是如何達成的程式片段:

<?php

/*把目錄改變到當前文件下*/
chdir(dirname(__FILE__));

/*Sprite 圖與圖的間距*/
$spriteGap = 30;


/*=[ 取得圖檔資訊 ]=*/
$maxWidth = 0;
$maxHeight = 0;
$nextTop = 0;
$imageList = array();

foreach ( glob('icons/*.{png,jpg,gif}',GLOB_BRACE) as $path )
{
    $image = new Imagick($path);
    $name = pathinfo($path,PATHINFO_FILENAME);

    if(isset($imageList[$name])){ 
        throw new Exception("圖片名稱重複 [ $name ]"); 
    }

    $info = array(
        '{top}' => $nextTop,
        '{image}' => $image,
        '{width}' => $image->getImageWidth(),
        '{height}' => $image->getImageHeight(),
        '{name}' => $name,
        '{path}' => $path,
        '{isAnimate}' => false
    );

    $header = '';
    switch($image->getImageFormat()){
        case "PNG":
            $header = 'data:image/png;base64,'; break;
        case "JPEG":
            $header = 'data:image/jpeg;base64,'; break;
        case "GIF":
            $header = 'data:image/gif;base64,'; break;
        default: break;
    }

    $info['{uri}'] = $header.base64_encode(file_get_contents($path));

    $maxWidth = max($maxWidth, $info['{width}']);
    $maxHeight = max($maxHeight, $info['{height}']);

    
    /*檢查圖片是否為動畫*/
    $frameNum = 0;
    foreach($image->deconstructImages() as $i) {
        $frameNum++;
        if ($frameNum > 1) {
            $info['{isAnimate}'] = true;
            break;
        }
    }
    
    if(!$info['{isAnimate}']){
        $nextTop += $info['{height}'] + $spriteGap;
    }


    $imageList[$name] = $info;
}


/*=[ 製作 CSS Sprite 圖檔 ]=*/
$spriteImage = new Imagick();
$spriteImage->newImage($maxWidth, $nextTop, new ImagickPixel());
$spriteImage->setImageFormat('png');
$spriteImage->paintTransparentImage(new ImagickPixel(), 0.0, 0);

foreach ($imageList as $name => $info)
{
    if($info['{isAnimate}']){ continue; } /* 忽略 GIF 動畫 */

    /* 複製 Icon 圖檔到 Sprite */
    $spriteImage->compositeImage(
        $info['{image}'],
        $info['{image}']->getImageCompose(),
        0,
        $info['{top}']
    );

    $info['{image}']->destroy();
    unset($imageList[$name]['{image}']);
}

$spriteImage->writeImage('icons.sprite.png');
$spriteImage->destroy();
$spriteImage = null;


下載完整程式: php_make_icons_css.zip
2013-07-07 13:29

[轉載][CSS] drop-shadows without images

轉載自:CSS drop-shadows without images

Lifted corners

Curled corners

Perspective

Raised box

Single vertical curve

Vertical curves

Single horizontal curve

Horizontal curves

Rotated box

2013-06-04 22:39

[轉載][CSS] 3D 立體文字

轉載自:3D Text

3D 立體文字


h1.title_3d { 
    color: #FFFFFF;
    font: bold 50px/1 "Helvetica Neue",Helvetica,Arial,sans-serif;
        
    text-shadow: 
        0 1px 0 #ccc, 
        0 2px 0 #c9c9c9, 
        0 3px 0 #bbb, 
        0 4px 0 #b9b9b9,
        0 5px 0 #aaa, 
        0 6px 1px rgba(0,0,0,.1), 
        0 0 5px rgba(0,0,0,.1), 
        0 1px 3px rgba(0,0,0,.3), 
        0 3px 5px rgba(0,0,0,.2), 
        0 5px 10px rgba(0,0,0,.25), 
        0 10px 10px rgba(0,0,0,.2), 
        0 20px 20px rgba(0,0,0,.15); 
} 

2013-05-29 21:23

[轉載] Default style sheet for HTML 4

轉載自:W3C Appendix D. Default style sheet for HTML 4

This appendix is informative, not normative.

This style sheet describes the typical formatting of all HTML 4 ([HTML4]) elements based on extensive research into current UA practice. Developers are encouraged to use it as a default style sheet in their implementations.

The full presentation of some HTML elements cannot be expressed in CSS 2.1, including replaced elements ("img", "object"), scripting elements ("script", "applet"), form control elements, and frame elements.

For other elements, the legacy presentation can be described in CSS but the solution removes the element. For example, the FONT element can be replaced by attaching CSS declarations to other elements (e.g., DIV). Likewise, legacy presentation of presentational attributes (e.g., the "border" attribute on TABLE) can be described in CSS, but the markup in the source document must be changed.

html, address,
blockquote,
body, dd, div,
dl, dt, fieldset, form,
frame, frameset,
h1, h2, h3, h4,
h5, h6, noframes,
ol, p, ul, center,
dir, hr, menu, pre   { display: block; unicode-bidi: embed; }

li              { display: list-item; }

head            { display: none; }

table           { display: table; }

tr              { display: table-row; }

thead           { display: table-header-group; }

tbody           { display: table-row-group; }

tfoot           { display: table-footer-group; }

col             { display: table-column; }

colgroup        { display: table-column-group; }

td, th          { display: table-cell; }

caption         { display: table-caption; }

th              { font-weight: bolder; text-align: center; }

caption         { text-align: center; }

body            { margin: 8px; }

h1              { font-size: 2em; margin: .67em 0; }

h2              { font-size: 1.5em; margin: .75em 0; }

h3              { font-size: 1.17em; margin: .83em 0; }

h4, p,
blockquote, ul,
fieldset, form,
ol, dl, dir,
menu            { margin: 1.12em 0; }

h5              { font-size: .83em; margin: 1.5em 0; }

h6              { font-size: .75em; margin: 1.67em 0; }

h1, h2, h3, h4,
h5, h6, b,
strong          { font-weight: bolder; }

blockquote      { margin-left: 40px; margin-right: 40px; }

i, cite, em,
var, address    { font-style: italic; }

pre, tt, code,
kbd, samp       { font-family: monospace; }

pre             { white-space: pre; }

button, textarea,
input, select   { display: inline-block; }

big             { font-size: 1.17em; }

small, sub, sup { font-size: .83em; }

sub             { vertical-align: sub; }

sup             { vertical-align: super; }

table           { border-spacing: 2px; }

thead, tbody,
tfoot           { vertical-align: middle; }

td, th, tr      { vertical-align: inherit; }

s, strike, del  { text-decoration: line-through; }

hr              { border: 1px inset; }

ol, ul, dir,
menu, dd        { margin-left: 40px; }

ol              { list-style-type: decimal; }

ol ul, ul ol,
ul ul, ol ol    { margin-top: 0; margin-bottom: 0; }

u, ins          { text-decoration: underline; }

br:before       { content: "\A"; white-space: pre-line; }

center          { text-align: center; }

:link, :visited { text-decoration: underline; }

:focus          { outline: thin dotted invert; }


/* Begin bidirectionality settings (do not change) */
BDO[DIR="ltr"]  { direction: ltr; unicode-bidi: bidi-override; }

BDO[DIR="rtl"]  { direction: rtl; unicode-bidi: bidi-override; }

*[DIR="ltr"]    { direction: ltr; unicode-bidi: embed; }

*[DIR="rtl"]    { direction: rtl; unicode-bidi: embed; }

@media print {
    h1            { page-break-before: always; }

    h1, h2, h3,
    h4, h5, h6    { page-break-after: avoid; }

    ul, ol, dl    { page-break-before: avoid; }
}
2012-06-04 01:29

[轉載] 自適應網頁設計

轉載自:自适应网页设计(Responsive Web Design) 阮一峰

随着 3G 的普及,越来越多的人使用手机上网。

移动设备正超过桌面设备,成为访问互联网的最常见终端。于是,网页设计师不得不面对一个难题:如何才能在不同大小的设备上呈现同样的网页?



手机的屏幕比较小,宽度通常在 600 像素以下,PC 的屏幕宽度,一般都在 1000 像素以上(目前主流宽度是1366×768),有的还达到了 2000 像素。同样的内容,要在大小迥异的屏幕上,都呈现出满意的效果,并不是一件容易的事。

很多网站的解决方法,是为不同的设备提供不同的网页,比如专门提供一个 mobile 版本,或者 iPhone / iPad 版本。这样做固然保证了效果,但是比较麻烦,同时要维护好几个版本,而且如果一个网站有多个 portal(入口),会大大增加架构设计的复杂度。

于是,很早就有人设想,能不能"一次设计,普遍适用",让同一张网页自动适应不同大小的屏幕,根据屏幕宽度,自动调整布局(layout)?




一、"自适应网页设计"的概念

2010 年,Ethan Marcotte 提出了"自适应网页设计"(Responsive Web Design)这个名词,指可以自动识别屏幕宽度、并做出相应调整的网页设计。

他制作了一个范例,里面是《福尔摩斯历险记》六个主人公的头像。如果屏幕宽度大于 1300 像素,则 6 张图片并排在一行。



如果屏幕宽度在 600 像素到 1300 像素之间,则 6 张图片分成两行。



如果屏幕宽度在 400 像素到 600 像素之间,则导航栏移到网页头部。



如果屏幕宽度在 400 像素以下,则 6 张图片分成三行。



mediaqueri.es 上面有更多这样的例子。

这里还有一个测试小工具,可以在一张网页上,同时显示不同分辨率屏幕的测试效果,我推荐安装。


二、允许网页宽度自动调整

"自适应网页设计"到底是怎么做到的?其实并不难。

首先,在网页代码的头部,加入一行 viewport元标签

<meta name="viewport" content="width=device-width, initial-scale=1" />

viewport 是网页默认的宽度和高度,上面这行代码的意思是,网页宽度默认等于屏幕宽度(width=device-width),原始缩放比例(initial-scale=1)为 1.0,即网页初始大小占屏幕面积的 100%。

所有主流浏览器都支持这个设置,包括 IE9。对于那些老式浏览器(主要是 IE6、7、8),需要使用 css3-mediaqueries.js

<!--[if lt IE 9]>
    <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->


三、不使用绝对宽度

由于网页会根据屏幕宽度调整布局,所以不能使用绝对宽度的布局,也不能使用具有绝对宽度的元素。这一条非常重要。

具体说,CSS代码不能指定像素宽度:

width: xxx px;

只能指定百分比宽度:

width: xx%;

或者

width: auto;


四、相对大小的字体

字体也不能使用绝对大小(px),而只能使用相对大小(em)。

body {
    font: normal 100% Helvetica, Arial, sans-serif;
}

上面的代码指定,字体大小是页面默认大小的 100%,即 16 像素。

h1 {
    font-size: 1.5em; 
}

然后,h1 的大小是默认大小的 1.5 倍,即 24 像素(24/16=1.5)。

small {
    font-size: 0.875em;
}

small 元素的大小是默认大小的 0.875 倍,即 14 像素(14/16=0.875)。


五、流动布局(fluid grid)

"流动布局"的含义是,各个区块的位置都是浮动的,不是固定不变的。

.main {
    float: right;
    width: 70%; 
}

.leftBar {
    float: left;
    width: 25%;
}

float 的好处是,如果宽度太小,放不下两个元素,后面的元素会自动滚动到前面元素的下方,不会在水平方向 overflow(溢出),避免了水平滚动条的出现。

另外,绝对定位(position: absolute)的使用,也要非常小心。


六、选择加载CSS

"自适应网页设计"的核心,就是 CSS3 引入的 Media Query 模块。

它的意思就是,自动探测屏幕宽度,然后加载相应的 CSS 文件。

<link rel="stylesheet" type="text/css" media="screen and (max-device-width: 400px)" href="tinyScreen.css" />

上面的代码意思是,如果屏幕宽度小于 400 像素(max-device-width: 400px),就加载 tinyScreen.css 文件。

<link rel="stylesheet" type="text/css" media="screen and (min-width: 400px) and (max-device-width: 600px)" href="smallScreen.css" />

如果屏幕宽度在 400 像素到 600 像素之间,则加载 smallScreen.css 文件。

除了用 html 标签加载 CSS 文件,还可以在现有 CSS 文件中加载。

@import url("tinyScreen.css") screen and (max-device-width: 400px);


七、CSS 的 @media 规则

同一个 CSS 文件中,也可以根据不同的屏幕分辨率,选择应用不同的 CSS 规则。

@media screen and (max-device-width: 400px) {
    .column {
        float: none;
        width: auto;
    }
    #sidebar {
        display: none;
    }
}

上面的代码意思是,如果屏幕宽度小于 400 像素,则 column 块取消浮动(float:none)、宽度自动调节(width:auto),sidebar 块不显示(display:none)。


八、图片的自适应(fluid image)

除了布局和文本,"自适应网页设计"还必须实现图片的自动缩放

这只要一行 CSS 代码:

img { max-width: 100%; }

这行代码对于大多数嵌入网页的视频也有效,所以可以写成:

img, object { max-width: 100%; }

老版本的 IE 不支持 max-width,所以只好写成:

img { width: 100%; }

此外,windows 平台缩放图片时,可能出现图像失真现象。这时,可以尝试使用 IE 的专有命令:

img { -ms-interpolation-mode: bicubic; }

或者,Ethan Marcotte 的 imgSizer.js

addLoadEvent(function() {
    var imgs = document.getElementById("content").getElementsByTagName("img");
    imgSizer.collate(imgs);
});

不过,有条件的话,最好还是根据不同大小的屏幕,加载不同分辨率的图片。有很多方法可以做到这一条,服务器端和客户端都可以实现。

(完)
2011-05-23 17:07

CSS Selector 優先權計算表

資料來源:小繁的blog
2011-05-19 13:16

Hotmail, Yahoo!Mail, Gmail 郵件CSS樣式表

轉載自:
Guide to CSS support in email clients - Articles & Tips - Campaign Monitor
CSS support in HTML emails of Hotmail, Yahoo! Mail and Gmail

style element Gmail Hotmail Yahoo! Mail
<style> element in the <head> No No Yes, but...
<style> element in the <body> No Yes, but... Yes, but...
link element Gmail Hotmail Yahoo! Mail
<link> element in the <head> No No No
<link> element in the <body> No No No
CSS selector Gmail Hotmail Yahoo! Mail
* untestable Yes Yes, but...
e untestable Yes Yes, but...
e > f untestable No Yes, but...
e:link untestable Yes Yes, but...
e:active, e:hover untestable Yes Yes, but...
e:focus untestable No Yes, but...
e:lang© untestable No Yes, but...
e+f untestable Yes Yes, but...
e[foo] untestable Yes Yes, but...
e.className untestable Yes Yes, but...
e#id untestable Yes Yes, but...
e:first-line untestable Yes Yes, but...
e:first-letter untestable Yes Yes, but...
CSS property Gmail Hotmail Yahoo! Mail
background-color Yes Yes Yes
background-image No Yes, but... Yes
background-position No No No
background-repeat No Yes Yes
border Yes Yes Yes
border-collapse Yes Yes Yes
border-spacing Yes No Yes
bottom No Yes Yes
caption-side Yes No Yes
clear No Yes Yes
clip No Yes, but... Yes, but...
color Yes Yes Yes
cursor No Yes Yes
direction Yes Yes Yes
display No Yes Yes
empty-cells Yes No Yes
filter No No Yes
float No Yes Yes
font-family No Yes Yes
font-size Yes Yes Yes
font-style Yes Yes Yes
font-variant Yes Yes Yes
font-weight Yes Yes Yes
height No Yes Yes
left No Yes Yes
letter-spacing Yes Yes Yes
line-height Yes Yes Yes
list-style-image No Yes, but... Yes
list-style-position Yes No No
list-style-type Yes Yes Yes
margin Yes No Yes
opacity No No Yes
overflow Yes Yes Yes
padding Yes Yes Yes
position No No No
right No Yes Yes
table-layout Yes Yes Yes
text-align Yes Yes Yes
text-decoration Yes Yes Yes
text-indent Yes Yes Yes
text-transform Yes Yes Yes
top No Yes Yes
vertical-align Yes Yes Yes
visibility No Yes Yes
white-space Yes Yes Yes
width Yes Yes Yes
word-spacing Yes Yes Yes
z-index No Yes Yes
Others Gmail Hotmail Yahoo! Mail
@import untestable No No
IE Mac hack No No Yes
javascript in url() No No No
url() No No Yes
Inline comments No No Yes
2011-01-18 16:15

CSS 常用命名表

版面類

欄目column
容器container
內容content
頁尾footer
頁首header
版型佈局layout
首頁index
頁面主體main
側欄sidebar

導航類

主導航main_nav
全域導航global_nav
導航nav
領行列navbar
左導航left_sidebar
右導航right_sidebar
子導航subnav
頂導航topnav
工具條toolbar

菜單類

菜單menu
子菜單submenu
菜單內容menu_content
菜單容器menu_container

樣式類

箭頭arrow
橫幅廣告banner
分界線boundary
按鈕btn
按鈕button
轉角/圓角corner
文字font
標題title
圖示icon
項目item
列表list
主要的master
頁面page
標示mark
分段section
邊導航圖標sidebar_icon
標籤頁tab
樣式/主題theme
閃爍twinkle
小部件widget
包裝器 wrapper
頁面外圍控制整體佈局寬度
區域zone

功能類

檢舉abuse
點擊這裡click_here
收藏coffin
塌陷collapse
完成的,結束的complete
改變,轉變conversion
當前的current
預設default
下載download
下拉drop
編輯edit
相等equals
例外exception
完成,結束finalize
折疊fold
雜湊hash
局部的localized
管理manager
方法method
即時通訊messenger
提示信息msg
註釋note
通知,告知;報告notify
語法分析parse
語法分析器parser
傳送pass
位置place
投票poll
發表文章post
預覽preview
列印print
發布publish
查詢query
收到,接到receive
重填reset
滾動scroll
搜索search
搜索框search_box
進階搜尋search_further
搜尋結果search_results
統計statistics
狀態status
串流stream
訂閱subscribe
送出submit
查詢訂閱subscriptions
小技巧tips
追蹤清單track
指導tutorial
上傳upload
驗證碼verification_code
觀看view
投票vote

內容類

檔案/文件archive
文章article
所有文章article_all
文章分類article_folder
招呼語blast
部落格blog
部落格資料blog_info
麵包屑bread_crumb
頁面所處位置導航提示
行事曆calendar
徵才careers
社群家族club
評論、評鑑comment
社群家族community
位置導航crumb
娛樂entertainment
電子報epaper
活動event
常見問題faq
回覆意見feedback
論壇forum
友情鏈接friend_link
強力搜尋gd_search_tech
留言板guestbook
指南guide
公會guild
熱門hot
熱門連結hot_link
學習learning
介紹introduce
徵才job
知識knowledge
新聞news
記事本notepad
即時訊息online_news
作品portfolio
活動比賽promo
排行rank
景點scenic
服務service
招呼語set_blast
即時留言板shoutbox
網頁導覽sitemap
技術支援support
旅遊travels
視訊video

網站類

關於about
關於我們about_us
公司company
公司簡介company_profile
聯絡contact
聯絡我們contact_us
版權資訊copyright
資訊info
網站標誌logo
商標label
組織organization
合作夥伴partner
薪資福利remuneration
摘要summary
系統system
網頁快訊web_slices

購物類

atmatm
現折活動allowance
配件appendix
紅利折抵bank_bonus
競標bid
取消訂單cancel
刷卡card
換貨change
推薦commend
優惠卷coupon
顧客customer
顧客服務customer_service
運送deliver
折扣discount
快速到貨express
購物流程flow
贈品gift
集殺group
詢價inquire
服務中心help
訂購單order
訂單查詢order_check
包裝packing
付費payment
集購payshop_flow
價格price
產品名稱product_name
產品products
嚴選保證promise
估價quotes
維修repair
退貨return
交易安全safety
購物shop
商店store
超商取貨付款store
補貨通知supply_info
信用卡線上分期time
統一編號unified business no.

會員類

通訊錄abook
帳務account
地址address
相簿album
申請apply
審核approval
黑名單black_list
信箱email
忘記密碼forgot_password
忘記帳號forgot_username
服務條款legal
登入login
登出logout
登入條login_bar
邀請朋友invite
加入join_us
會員member
會員登入member_login
個人personal
個人資訊personal_information
照片photo
隱私權政策privacy
個人簡介profile
個人相片profile_photo
註冊register
轉寄好友send_friend
註冊sign_up
登入sign_in
登出sign_out


參考來源:
CSS 常用命名参考 - PHP新手博客(phpabc‘s blog)
css常用命名
div+css命名规则 (注重SEO的朋友注意了)
Jane’s Blog: CSS 命名規則
2010-09-12 02:12

用 PhotoShop JSX 製作 CSS Sprite 的使用方法

自從上一篇 利用 PhotoShop 製作 CSS Sprite 發佈後我又改了 JSX 好幾次,現在終於修到讓我自己滿意了,順便來寫一下使用方法。

由於我的 PhotoShop 是 CS2 的,太舊的版本可能會沒有 Script 的功能,在這裡先聲明一下。

檔案連結:css_sprite_ps-script.jsx


  1. 先將所有需要組合的圖檔開啟


  2. 選擇『檔案 -> 指令碼 -> 瀏覽』


  3. 選擇下載後的 css_sprite_ps-script.jsx


  4. 接著馬上會要你選擇一個要參考的原始 CSS,這裡會解析你原本的樣式名稱跟檔案對應,當然不選也沒關係。
    解析 CSS 是用正規表示式去解析的,可能要花一點時間,我餵了一個兩千行的 CSS file 都還可以正常執行,再多我就不敢保證了。


  5. 我原始的 CSS 看起來像是這樣,當然稍微複雜一點內容應該也沒問題。


  6. 在圖片處理完後,會要選擇一個輸出定位的 CSS file


  7. 輸出的內容看起來會像是這樣


  8. 最後再將製作完成的圖檔存成自己需要的格式就可以了
2010-09-01 23:50

利用 PhotoShop 製作 CSS Sprite

原本想用 PhotoShop 的巨集來製作 CSS Sprite 的圖片,但沒想到巨集沒辦法很方便的匯入圖片到圖層上,最後找到一個可行的方法就是寫 PhotoShop 的 Script。

我只有兩個需求:
  • 處理圖檔組合
  • 紀錄每張圖的起始定位
雖然已經寫完了,但是還是有一些小小的 Bug,對於透明底色的 png 會有定位上的偏差,我的解決辦法就是在四個角畫上 1px 透明為 1% 的白色,雖然美中不足但勉強夠用。
這個小 Bug 已經解決了。


這個 Script 的執行方式很簡單
只要將需要合併的圖檔全部開啟
接著『檔案 -> 指令碼 -> 瀏覽』選擇下載後的 css_sprite_ps-script.jsx
執行後會建立一個新圖檔,並且要選擇輸出的 CSS 的檔案名稱


// css_sprite_ps-script.jsx
#target photoshop

/** 建立參考線
* @param {Int} pixelOffSet 偏移像素
* @param {String} orientation ["Vrtc" => 垂直 ,"Hrzn" => 水平]
*/
function makeGuide(pixelOffSet, orientation) {
var id8 = charIDToTypeID( "Mk " );
var desc4 = new ActionDescriptor();
var id9 = charIDToTypeID( "Nw " );
var desc5 = new ActionDescriptor();
var id10 = charIDToTypeID( "Pstn" );
var id11 = charIDToTypeID( "#Rlt" );
desc5.putUnitDouble( id10, id11, pixelOffSet ); // integer
var id12 = charIDToTypeID( "Ornt" );
var id13 = charIDToTypeID( "Ornt" );
var id14 = charIDToTypeID( orientation ); // "Vrtc", "Hrzn"
desc5.putEnumerated( id12, id13, id14 );
var id15 = charIDToTypeID( "Gd " );
desc4.putObject( id9, id15, desc5 );
executeAction( id8, desc4, DialogModes.NO );
}

function main(){
//判斷是否有開啟圖檔
if (app.documents.length = 0) {return;}

//設定前景色為白色
app.foregroundColor.rgb.hexValue = 'FFFFFF';

var atDoc;
var list = [];
var length = app.documents.length;

//新增目標圖片文件
var newPic = app.documents.add(
1, 1, 72,
"css_sprite",
NewDocumentMode.RGB,
DocumentFill.TRANSPARENT
);

var height=0;
var width = newPic.width;
//複製所有圖檔至新建立的圖檔
for (var i=0; i<length; i++){
atDoc=app.activeDocument=app.documents[i];

//記錄圖層資訊
var newLayer={
name: atDoc.name, //檔名
width: atDoc.width,
height: atDoc.height,
top: height
};

//累計高度
height += app.documents[i].height.value;
//最大寬度
if(width < atDoc.width){ width=atDoc.width;}

//新增圖層
var aLayer = atDoc.activeLayer=atDoc.artLayers.add();

//複製背景底圖
try {
atDoc.backgroundLayer.duplicate(aLayer,ElementPlacement.PLACEAFTER);
atDoc.backgroundLayer.remove();
} catch (e){}

//將新圖層與下一層互換
aLayer.move(atDoc.layers[1],ElementPlacement.PLACEAFTER);

//標註四周的定位點
var w=atDoc.width.value, h=atDoc.height.value;
atDoc.selection.select([[0,0],[1,0],[1,1],[0,1],[0,0]]);
atDoc.selection.fill(app.foregroundColor)
atDoc.selection.select([[0,h-1],[0,h],[1,h],[1,h-1],[0,h-1]]);
atDoc.selection.fill(app.foregroundColor)
atDoc.selection.select([[w-1,0],[w-1,1],[w,1],[w,0],[w-1,0]]);
atDoc.selection.fill(app.foregroundColor)
atDoc.selection.select([[w-1,h-1],[w-1,h],[w,h],[w,h-1],[w-1,h-1]]);
atDoc.selection.fill(app.foregroundColor)

//設定透明度
aLayer.fillOpacity=1;
//合併可見圖層
atDoc.mergeVisibleLayers();
//複製圖層
atDoc.selection.selectAll()
atDoc.selection.copy()

//貼上圖層
atDoc=app.activeDocument=newPic;
newLayer.obj = atDoc.paste();
list.push(newLayer);
};

//變更圖片大小
atDoc=app.activeDocument=newPic;
atDoc.resizeCanvas(width,height,AnchorPosition.TOPLEFT);

//變更圖層定位
for (var i=length-1; i>=0; i--){
//關閉複製過的檔案
app.documents[i].close(SaveOptions.DONOTSAVECHANGES);

//移動圖層
list[i].obj.translate(0,list[i].top);

//建立參考線
if(i>0){ makeGuide(list[i].top,"Hrzn"); }
};

// 輸出 CSS 定位檔
var mySavefile = File.saveDialog("輸出 CSS 定位檔","*.css");
if(!mySavefile){return};
if(mySavefile.exists && !confirm("你確定要覆蓋這個檔案?")){
return false;
}
// 開啟檔案
var fileRef = new File(mySavefile);
if (!fileRef.open("w","","")){
alert("無法開啟檔案!!");
fileRef.close();
return false;
}

// 輸出 CSS 定位設定
for (var i=0; i<list.length; i++){
fileRef.writeln(
list[i].name+'{ background-position: 0 -'+list[i].top+'px; }'
);
};
fileRef.close();
}


//把Photoshop推到最上層
app.bringToFront();
//設定使用的單位為「像素(Pixel)」
app.preferences.rulerUnits = Units.PIXELS;

main();


檔案下載:css_sprite_ps-script.jsx


有對這個興趣的朋友可以參考 PhotoShop 安裝目錄下的 "JavaScript Reference Guide.pdf" 的開發文件,雖然裡面全部都是英文的但還不置於看不懂。
2010-05-22 14:50

CSS3 圓角

*{

/* Gecko browsers */
-moz-border-radius: 20px; /*all*/
-moz-border-radius: 20px 0; /*TL&BR, TR&BL*/
-moz-border-radius: 20px 0 20px; /*TL, TR&BL, BR*/
-moz-border-radius: 20px 0 20px 0; /*TL, TR, BR, BL*/
-moz-border-radius: 20px/ 10px; /*(X)/ (Y)*/
-moz-border-radius: 20px 0 20px 0/ 10px 0 10px 0; /*(X)TL, TR, BR, BL/ (Y)TL, TR, BR, BL*/

-moz-border-radius-topleft: 20px;
-moz-border-radius-topright: 0;
-moz-border-radius-bottomright: 20px;
-moz-border-radius-bottomleft: 0;


/* Webkit browsers */
-webkit-border-radius: 20px; /*all*/
-webkit-border-radius: 20px 0 20px 0; /*TL, TR, BR, BL*/

-webkit-border-top-left-radius: 20px;
-webkit-border-top-right-radius: 0;
-webkit-border-bottom-right-radius: 20px;
-webkit-border-bottom-left-radius: 0;


/* Konqueror (KDE) */
-khtml-border-radius: 20px; /*all*/
-khtml-border-radius: 20px 0 20px 0; /*TL, TR, BR, BL*/

-khtml-border-top-left-radius: 20px;
-khtml-border-top-right-radius: 20px;
-khtml-border-bottom-left-radius: 20px;
-khtml-border-bottom-right-radius: 20px;


/* ??? browsers */
-goog-ms-border-radius: 20px; /*all*/
-goog-ms-border-radius: 20px 0 20px 0;/*TL, TR, BR, BL*/

-goog-ms-border-top-left-radius: 20px;
-goog-ms-border-top-right-radius: 0;
-goog-ms-border-bottom-right-radius: 20px;
-goog-ms-border-bottom-left-radius: 0;


/* W3C syntax */
border-radius: 20px; /*all*/
border-radius: 20px 0; /*TL&BR, TR&BL*/
border-radius: 20px 0 20px; /*TL, TR&BL, BR*/
border-radius: 20px 0 20px 0; /*TL, TR, BR, BL*/
border-radius: 20px/ 10px; /*(X)/ (Y)*/
border-radius: 20px 0 20px 0/ 10px 0 10px 0; /*(X)TL, TR, BR, BL/ (Y)TL, TR, BR, BL*/

border-top-left-radius: 20px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius:  20px;

}


參考來源:
CSS Backgrounds and Borders Module Level 3
CSS Border Radius :: Richard A. Johnson
border-radius與圓角 - wowbox blog (網頁設計知識庫)
2010-05-22 13:40

CSS 偽類 與 偽元素

:link
未被訪問過的連結
IE6, FF3, Safari3, Chrome5, Opera
:visited
已被訪問過的連結
IE6, FF3, Safari3, Chrome5, Opera
:hover
滑鼠重疊時(mouse over)
IE7, FF3, Safari3, Chrome5, Opera
:active
元素被按下時(mouse down)
IE6, FF3, Safari3, Chrome5, Opera
:focus
元素被選擇時
IE8, FF3, Safari3, Chrome5, Opera
:first-line
區塊內的第一行
IE7, FF3, Safari3, Chrome5, Opera
:first-letter
區塊內的第一個字
IE7, FF3, Safari3, Chrome5, Opera
:first-child
元素為第一個項目時
IE7, FF3, Safari3, Chrome5, Opera
:last-child
元素為最後一個項目時
IE9, FF3, Safari3, Chrome5, Opera
:lang
指定元素中使用的語言
IE6, FF3, Safari3, Chrome5, Opera
:before
區塊內最前面加入一個虛擬元素
IE8, FF3, Safari3, Chrome5, Opera
:after
區塊內最後面加入一個虛擬元素
IE8, FF3, Safari3, Chrome5, Opera


參考來源:
CSS Selectors and Pseudo Selectors and browser support
Web Browser CSS Support
2009-12-22 14:40

CSS 部屬經驗-圖文列表樣式

樣式



HTML 結構

<ul class="Img2HList ClearIt">
<li class="List Odd">
<div class="Container">
<strong class="Title">
<a><span class="Image"><img src="圖片網址" /></span>標題文字</a>
</strong>

<!--其他相關資訊-->
<p class="Info">描述文字</p>
<div class="Meta">文字</div>
<blockquote>文字</blockquote>
</div>
</li>
<li class="List">
<div class="Container">
<strong class="Title">
<a><span class="Image"><img src="圖片網址" /></span>標題文字</a>
</strong>

<!--其他相關資訊-->
<p class="Info">描述文字</p>
<div class="Meta">文字</div>
<blockquote>文字</blockquote>
</div>
</li>
</ul>



CSS 設定

ul.Img2HList {
margin: 1em 0;
overflow: hidden;
}
ul.Img2HList li.List {
position:relative;
display: block;
float: left;
width: 49%;
margin: 0 0 30px 0;
font-size: 11px;
}
ul.Img2HList .Container {
padding: 0 0 0 79px;
}
ul.Img2HList li.Odd {
clear: left;
}
ul.Img2HList li.Odd .Container{
margin-right: 30px;
}
ul.Img2HList strong.Title {
display: block;
font-size:1.1em;
border-bottom: 1px solid #ccc;
}
ul.Img2HList strong.Title span.Image {
float: left;
margin: 0 0 0 -79px;
cursor: pointer;
}



參考頁面:
Last.fm
Wacanai.com