How to create a simple HTML page with a horizontally and vertically centered image

Written by - 0 comments

Published on - Listed in HTML Internet


Originally coming from the world of HTML and web-publishing, it's been a while since I actually needed to do a HTML page. For a quick project I wanted to create a very simple page, just showing a centered image in the middle of the page.

Of course the "<center>" tag is still present in my head (once you ride a bicycle...), but this only centers the image (or text, or whatever is embedded within the <center> tag) horizontally, not vertically. Depending on screen size, this can look weird.

In the past I would've probably used a stretched table, spanning 100% in width and height, however there's a much better solution.

The following CSS can be used to center any image on the page:

$ cat css.css
img {
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

The full HTML of the index page (which uses the previous css):

# cat index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>PDF Download</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="content-language" content="en">
<link href="/css.css" rel="stylesheet">
<meta name="theme-color" content="#ffffff">
</head>
<body>
<a href="document.pdf" target="_blank"><img src="pdf.png"></a>
</body>
</html>

The resulting page shows the image centered in the browser window:

HTML centered (both vertically and horizontally) image

Even after a browser resize (larger window), the image remains centered:

Note: The size of the image is not automatically scaled. That would be another task.


Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.

RSS feed

Blog Tags:

  AWS   Android   Ansible   Apache   Apple   Atlassian   BSD   Backup   Bash   Bluecoat   CMS   Chef   Cloud   Coding   Consul   Containers   CouchDB   DB   DNS   Database   Databases   Docker   ELK   Elasticsearch   Filebeat   FreeBSD   Galera   Git   GlusterFS   Grafana   Graphics   HAProxy   HTML   Hacks   Hardware   Icinga   Influx   Internet   Java   KVM   Kibana   Kodi   Kubernetes   LVM   LXC   Linux   Logstash   Mac   Macintosh   Mail   MariaDB   Minio   MongoDB   Monitoring   Multimedia   MySQL   NFS   Nagios   Network   Nginx   OSSEC   OTRS   Office   PGSQL   PHP   Perl   Personal   PostgreSQL   Postgres   PowerDNS   Proxmox   Proxy   Python   Rancher   Rant   Redis   Roundcube   SSL   Samba   Seafile   Security   Shell   SmartOS   Solaris   Surveillance   Systemd   TLS   Tomcat   Ubuntu   Unix   VMWare   VMware   Varnish   Virtualization   Windows   Wireless   Wordpress   Wyse   ZFS   Zoneminder