惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

CSS Wizardry

Front-End’s Missing Metric: The TBT Window Meet Your Users Where They Are with Obs.js Better Browser Caching with No-Vary-Search font-family Doesn’t Fall Back the Way You Think What Is CSS Containment and How Can I Use It? When All You Can Do Is All or Nothing, Do Nothing Obs.js: Context-Aware Web Performance for Everyone Low- and Mid-Tier Mobile for the Real World (2025) The Fastest Site in the Tour de France Making Sense of the Performance Extensibility API Why Do We Have a Cache-Control Request Header? HTML Is Not a Programming Language… Build for the Web, Build on the Web, Build with the Web Licensing Code on CSS Wizardry A Layered Approach to Speculation Rules Designing (and Evolving) a New Web Performance Score Core Web Vitals Colours The Ultimate Contract Templates for Tech Consultants: Protect Your Business and Get Paid Optimising for High Latency Environments Cache Grab: How Much Are You Leaving on the Table? blocking=render: Why would you do that?! Correctly Configure (Pre) Connections The Three Cs: 🤝 Concatenate, 🗜️ Compress, 🗳️ Cache What Is the Maximum max-age? How to Clear Cache and Cookies on a Customer’s Device The Ultimate Low-Quality Image Placeholder Technique Core Web Vitals for Search Engine Optimisation: What Do We Need to Know? The HTTP/1-liness of HTTP/2 In Defence of DOM­Content­Loaded Site-Speed Topography Remapped Why Not document.write()? Speeding Up Async Snippets Critical CSS? Not So Fast! Measure What You Impact, Not What You Influence Optimising Largest Contentful Paint Measuring Web Performance in Mobile Safari Site-Speed Topography Speed Up Google Fonts Real-World Effectiveness of Brotli Performance Budgets, Pragmatically Lazy Pre-Browsing with Prefetch Making Cloud.typography Fast(er) Time to First Byte: What It Is and How to Improve It Self-Host Your Static Assets Tips for Technical Interviews Cache-Control for Civilians Bandwidth or Latency: When to Optimise for Which ITCSS × Skillshare What If? CSS and Network Performance The Three Types of Performance Testing Getting to Know a Legacy Codebase Image Inconsistencies: How and When Browsers Download Images Identifying, Auditing, and Discussing Third Parties My Digital Music Setup Measuring the Hard-to-Measure Finding Dead CSS The Fallacies of Distributed Computing (Applied to Front-End Performance) Ten Years Old Relative Requirements Airplanes and Ashtrays Performance and Resilience: Stress-Testing Third Parties Refactoring Tunnels Little Things I Like to Do with Git Writing Tidy Code Configuring Git and Vim Base64 Encoding & Performance, Part 2: Gathering Data Base64 Encoding & Performance, Part 1: What’s Up with Base64? Code Smells in CSS Revisited Typography for Developers Moving CSS Wizardry onto HTTPS and HTTP/2 Ack for CSS Developers A New Year, a New Focus Preparing Vim for Apple’s Touch Bar Choosing the Correct Average CSS Shorthand Syntax Considered an Anti-Pattern CSS Wizardry Newsletter Nesting Your BEM? Improving Perceived Performance with Multiple Background Images Continue Normalising Your CSS Pure CSS Content Filter Pragmatic, Practical, and Progressive Theming with Custom Properties Refactoring CSS: The Three I’s Speaker’s Checklist: Before and After Your Talk Improving Your CSS with Parker The Importance of !important: Forcing Immutability in CSS Mixins Better for Performance Managing Typography on Large Apps White October Events Workshop Partnership BEMIT: Taking the BEM Naming Convention a Step Further Travelling Like You Want to, When You Have To Contextual Styling: UI Components, Nesting, and Implementation Detail Subtleties with Self-Chained Classes Cyclomatic Complexity: Logic in CSS Immutable CSS Can CSS Be Too Modular? More Transparent UI Code with Namespaces When to use @extend; when to use a mixin The Specificity Graph CSS Wizardry Ltd.: Year 1 in review
iPhone CSS—tips for building iPhone websites
Harry Roberts · 2010-02-01 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. To start
    1. Saving to the homescreen – shortening the page title
    2. Stopping user pinch-zooming
  2. Beginning styling
    1. Things to remember
    2. Structure
    3. The navigation
    4. Images

With the rapid rise in mobile browsers, it has probably never been more important to ensure your sites can be handled on these platforms. By far one of the most popular such browsers is Mobile Safari on the iPhone – this is one of the easiest browsers to develop for: it runs on Webkit (meaning a lot of rich CSS3 support) and it’s only ever on one resolution and on one OS.

N.B. This article addresses iPhone development and iPhone development only. There is no reason why you cannot or should not develop for other mobile devices and platforms, Apple or otherwise. This just happens to be an iPhone only post.

The practical upshot of this is that you need to do no cross-browser testing, and can use all the CSS3 you like. This post will show you some of the basics of developing and designing websites for the iPhone and Mobile Safari.

To start

The first thing to remember when developing a site to be displayed on an iPhone is that it is very similar to designing a print stylesheet. You need to linearise everything. Make sure you have one column and everything is read in one line – straight from top to bottom. This will also put your markup writing skills to the test.

Some people don’t agree with browser sniffing, but you need to detect the iPhone somehow.

This first bit of code is a PHP browser sniffing snippet, the actual CSS we’ll use is not brought through via any server side code, we’ll use some CSS media queries for that. What we’ll use this code for is serving the markup with an iPhone specific meta tag and to shorten the current page’s title.

<?php
  $browser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    if ($browser == true){
    $browser = 'iphone';
  }
?>

What the above code does is sees if the user agent contains any instance of ‘iPhone’ using the strpos PHP function. Place this piece of code at the very top of your header include, before any other markup. In order to action something if the browser is an iPhone, simply use the following bit of PHP logic in the place you want it to be initiated:

<?php if($browser == 'iphone'){ ?>DO THIS<?php } ?>

We want people to save your site to their home screen…

Now, to put that snippet to use. We want to do two things with this little piece of PHP.

Saving to the homescreen – shortening the page title

First off, we’d like users to be able to save a link to your site on their home screen, this is simple enough, they simply need to select to do so from within the browser. However, if you look at the title of my home page alone, it’s quite long: CSS Wizardry – CSS, Web Standards, Typography, and Grids by Harry Roberts. This would never fit underneath an icon without being shortened, so we need to serve a different title to the iPhone only. To achieve this we us the PHP snippet like so:

<?php if($browser == 'iphone'){ ?>
  <title>Short iPhone only title</title>
<?php }else{ ?>
  <title>Regular title</title>
<?php } ?>

Now, both when browsing and saving your site to their home screen, a user will only ever see the shortened version.

The home screen icon

Actually making the icon is very simple. All you need to do is upload a 57x57px icon (usually a larger version of your favicon) to your server root. The icon must be named apple-touch-icon.png, and the iPhone will sort the rest out.

Stopping user pinch-zooming

The second use for the PHP snippet is to serve the iPhone a meta tag which disables the user pinch-zoom that Mobile Safari offers:

<?php if($browser == 'iphone'){ ?>
  <meta name="viewport"
  content="width=device-width,
  minimum-scale=1.0, maximum-scale=1.0" />
<?php } ?>

This means that, once we’ve linearised the content and sorted the font sizing, the user will only ever have to traverse down your page, much like a native app.

Beginning styling

Some developers prefer to redirect iPhone users to a totally different version of the site – we won’t be doing that.

We could use the PHP snippet to serve the iPhone a whole new stylesheet, or even send the user to a whole new site, rather like Twitter does (m.twitter.com). However, there’s a simpler way to do it using some CSS media queries. The advantage of this is that you’re simply reusing old content and pre-written markup, and only ever using one CSS file.

The first thing you need to do is make sure the HTML link element that points to your main stylesheet does not have a media attribute:

<link rel="stylesheet" href="/path/to/style.css">

Next, we’re going to use Quick Tip #15 that I wrote on my Quick Tips page. This means that we can just add our iPhone styles directly onto the end of the main stylesheet, and inherit all the styles set for desktop viewing:

/*--- Main CSS here ---*/

/*------------------------------------*\
	$IPHONE
\*------------------------------------*/
@media screen and (max-device-width: 480px){
    /*--- iPhone only CSS here ---*/
}

Now any CSS before the media query will be used across all platforms, but anything between the query will be used by any screen media with a maximum screen size of 480px (i.e. an iPhone).

Things to remember

There are a few key things to remember when developing CSS for the iPhone:

  • Avoid explicit absolute widths – where possible you should use percentage widths.
  • Linearise everything – where possible, remove all floats. We want no content side-by-side unnecessarily.

The first thing to do is to set the -webkit proprietary CSS -webkit-text-size-adjust on the body which will resize the text for you, meaning you shouldn’t have to touch any font sizes yourself. Also, if your body copy is set in a sans font such as Arial, now is your chance to use some Helvetica – for normal sites, Helvetica should not be used as body copy as it renders hideously on a PC. Take advantage of the fact that you can guarantee its presence and quality on an iPhone. Change your font-family:

/*--- Main CSS here ---*/

/*------------------------------------*\
	$IPHONE
\*------------------------------------*/
@media screen and (max-device-width: 480px){
    body{
        -webkit-text-size-adjust:none;
        font-family:Helvetica, Arial, Verdana, sans-serif;
        padding:5px;
    }
}

Above, I also added a small padding to make sure nothing touches the edge of the browser. All wrapper and content divs from here on in should be set to width:100%; making them the whole width of the screen, minus 10px.

Structure

Now, as all layouts differ I am going to assume a similar one to mine, a simple two column set up with a logo and menu in the header. If your layout is different I am sure you can quite easily retrofit it. As I mentioned before, remove all stylistic floats and set all widths to 100%. If you are using divs sensibly (i.e. for large bodies of content and not for nav items) this code should see you right for linearising the content:

@media screen and (max-device-width: 480px){
    body{...}
    div{
        clear:both!important;
        display:block!important;
        width:100%!important;
        float:none!important;
        margin:0!important;
        padding:0!important;
    }
}

That will force all divs to rest one on top of the other, full width and in order. You have begun linearising all your content.

The navigation

If you have a navigation menu in which all the items are floated and made horizontal, insert the following:

@media screen and (max-device-width: 480px){
    body{...}
    div{...}
    #nav,#nav li{
        float:none!important;
        clear:both!important;
        margin:0 0 20px 0!important;
        display:block;
        padding:0;
        text-align:left!important;
        width:100%;
    }
    #nav{
        border:1px solid #ccc;
        padding:5px;
        border-radius:5px;
    }
    #nav li{
        margin:0!important;
    }
    #nav li a{
        display:block;
    }
}

This then will give you a vertical navigation menu which has a 100% width and the actual links themselves have a larger hit area (applied via display:block;), meaning that it’s prominent at the top of each page and easier for users to select single items.

Images

As images inherently have a set pixel width (i.e. their own width) there is a high chance that they will break out of the wrapper area (as a lot of images will be above 480px wide). To combat this simply add the following:

@media screen and (max-device-width: 480px){
    body{...}
    div{...}
    #nav,#nav li{...}
    img{
        max-width:100%;
        height:auto;
    }
}

Other than elements very specific to my site, that is pretty much all the CSS I use to quickly size and linearise my content. Any elements specific to your own site will obviously need considering on a case-by-case basis, but if you remember to not set absolute widths and to always linearise your content then it should be a doddle. Oh and it’s a great time to use some guaranteed CSS3.

Do you have an iPhone version of your site? Have you any more tips you’d like to add? Please do so in the comments below.