Learn CSS #38 Part 1/2

CSS Image Gallery


CSS can be used to create an image gallery.

Cinque Terre

Add a description of the image here
Forest

Add a description of the image here
Northern Lights

Add a description of the image here
Mountains

Add a description of the image here

Image Gallery

The following image gallery is created with CSS:

Example

<html>
<head>
<style>
div.gallery {
  margin: 5px;
  border: 1px solid #ccc;
  float: left;
  width: 180px;
}

div.gallery:hover {
  border: 1px solid #777;
}

div.gallery img {
  width: 100%;
  height: auto;
}

div.desc {
  padding: 15px;
  text-align: center;
}
</style>
</head>
<body>

<div class="gallery">
  <a target="_blank" href="img_5terre.jpg">
    <img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  <a target="_blank" href="img_forest.jpg">
    <img src="img_forest.jpg" alt="Forest" width="600" height="400">
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  <a target="_blank" href="img_lights.jpg">
    <img src="img_lights.jpg" alt="Northern Lights" width="600" height="400">
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  <a target="_blank" href="img_mountains.jpg">
    <img src="img_mountains.jpg" alt="Mountains" width="600" height="400">
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

</body>
</html>

More Examples

Responsive Image Gallery

How to use CSS media queries to create a responsive image gallery that will look good on desktops, tablets and smart phones.


CSS Image Sprites


Image Sprites

An image sprite is a collection of images put into a single image.

A web page with many images can take a long time to load and generates multiple server requests.

Using image sprites will reduce the number of server requests and save bandwidth.


Image Sprites – Simple Example

Instead of using three separate images, we use this single image (“img_navsprites.gif”):

navigation images

With CSS, we can show just the part of the image we need.

In the following example the CSS specifies which part of the “img_navsprites.gif” image to show:

Example

#home {
  width: 46px;
  height: 44px;
  background: url(img_navsprites.gif) 0 0;
}

Example explained:

  • <img id="home" src="img_trans.gif"> – Only defines a small transparent image because the src attribute cannot be empty. The displayed image will be the background image we specify in CSS
  • width: 46px; height: 44px; – Defines the portion of the image we want to use
  • background: url(img_navsprites.gif) 0 0; – Defines the background image and its position (left 0px, top 0px)

This is the easiest way to use image sprites, now we want to expand it by using links and hover effects.


Image Sprites – Create a Navigation List

We want to use the sprite image (“img_navsprites.gif”) to create a navigation list.

We will use an HTML list, because it can be a link and also supports a background image:

Example

#navlist {
  position: relative;
}

#navlist li {
  margin: 0;
  padding: 0;
  list-style: none;
  position: absolute;
  top: 0;
}

#navlist li, #navlist a {
  height: 44px;
  display: block;
}

#home {
  left: 0px;
  width: 46px;
  background: url('img_navsprites.gif') 0 0;
}

#prev {
  left: 63px;
  width: 43px;
  background: url('img_navsprites.gif') -47px 0;
}

#next {
  left: 129px;
  width: 43px;
  background: url('img_navsprites.gif') -91px 0;
}

Example explained:

  • #navlist {position:relative;} – position is set to relative to allow absolute positioning inside it
  • #navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;} – margin and padding are set to 0, list-style is removed, and all list items are absolute positioned
  • #navlist li, #navlist a {height:44px;display:block;} – the height of all the images are 44px

Now start to position and style for each specific part:

  • #home {left:0px;width:46px;} – Positioned all the way to the left, and the width of the image is 46px
  • #home {background:url(img_navsprites.gif) 0 0;} – Defines the background image and its position (left 0px, top 0px)
  • #prev {left:63px;width:43px;} – Positioned 63px to the right (#home width 46px + some extra space between items), and the width is 43px.
  • #prev {background:url(‘img_navsprites.gif’) -47px 0;} – Defines the background image 47px to the right (#home width 46px + 1px line divider)
  • #next {left:129px;width:43px;}- Positioned 129px to the right (start of #prev is 63px + #prev width 43px + extra space), and the width is 43px.
  • #next {background:url(‘img_navsprites.gif’) -91px 0;} – Defines the background image 91px to the right (#home width 46px + 1px line divider + #prev width 43px + 1px line divider )

Image Sprites – Hover Effect

Now we want to add a hover effect to our navigation list.

Tip: The :hover selector can be used on all elements, not only on links.

Our new image (“img_navsprites_hover.gif”) contains three navigation images and three images to use for hover effects:

navigation images

Because this is one single image, and not six separate files, there will be no loading delay when a user hovers over the image.

We only add three lines of code to add the hover effect:

Example

#home a:hover {
  background: url('img_navsprites_hover.gif') 0 -45px;
}

#prev a:hover {
  background: url('img_navsprites_hover.gif') -47px -45px;
}

#next a:hover {
  background: url('img_navsprites_hover.gif') -91px -45px;
}

Example explained:

  • #home a:hover {background: url(‘img_navsprites_hover.gif’) 0 -45px;} – For all three hover images we specify the same background position, only 45px further down

Categories

83 Responses

  1. 5 mg, 5 mg, 10 mg, and 20 mg tablets online cialis In a recent comprehensive review that summarized data obtained in 20 community- and clinical-based studies of 71,322 men, a positive correlation between LUTS and ED was demonstrated, with the overall ORs ranging from 1

  2. com 20 E2 AD 90 20Dosis 20Viagra 20Segun 20Peso 20 20Lowest 20Price 20For 20Viagra 20Online dosis viagra segun peso The following are trademarks or service marks of Major League Baseball entities and may be used only with permission of Major League Baseball Properties, Inc tamoxifen retinopathy

  3. minoxidil vs propecia com 20 E2 AD 90 20Viagra 20Scaduto 20Fa 20Male 20 20Can 20I 20Buy 20Viagra 20Over 20The 20Counter can i buy viagra over the counter His notebooks are a map of the subconscious, and his films doorways into the dungeons of our dreams, allowing us to confront our own individual hearts of darkness, to do battle and emerge victorious, Cameron added

  4. Hello bro!More info>>>
    сеть пансионатов
    https://pansionat-rnd.ru/
    “Дом престарелых” – это общепринятое название для социального учреждения, которое оказывает услуги по социальной защите и помощи престарелым людям. Если вы ищете информацию о конкретном доме престарелых в Ростове-на-Дону, можете уточнить местоположение и другую информацию.
    пансионат для пожилых людей

  5. Vardenafil es un medicamento utilizado para tratar la disfuncion erectil en los hombres. Fue aprobado por la FDA en 2003 y es una opcion efectiva para aquellos que buscan para que es la levitra tratamiento para la disfuncion erectil.
    Vardenafil levitra precio en argentina esta disponible en las farmacias con receta medica. Es importante consultar con un medico antes de comprar Vardenafil para asegurarse de que sea seguro y efectivo para su uso. Ademas, tambien se puede comprar Vardenafil en linea a traves de farmacias en linea confiables y autorizadas.
    En resumen, Vardenafil es una opcion eficaz para aquellos que buscan tratamiento para la disfuncion erectil. Ofrece mejoras en la calidad de la ereccion levitra online , es facil de usar y es una opcion discreta y comoda. Consulte con un medico antes de comprar Vardenafil para asegurarse de que sea seguro y adecuado para su uso.
    Vardenafil levitra precio en farmacia es una opcion discreta para aquellos que buscan tratamiento para la disfuncion erectil. Es posible tomarlo con discrecion y sin tener que preocuparse por el uso de dispositivos o la realizacion de procedimientos invasivos.
    cialis 5 mg
    reduslim mercadona

  6. Hello bro!More info>>>
    пансионат для престарелых
    https://pansionat-rnd.ru/
    Пансионат для пожилых людей – это тип жилья для престарелых, где они могут жить независимо, но получать регулярную медицинскую и социальную помощь. Пансионаты обычно оборудованы спальнями и комнатами для общения, а также обеспечивают питание, гигиену и уборку. В некоторых случаях может быть предоставлена реабилитация и развлекательные мероприятия. Пансионаты могут быть общественными или частными и обычно имеют высокую оплату за жилье и услуги.
    частный пансионат

    http://images.google.com.om/url?q=https://pansionat-rnd.ru/ http://cse.google.st/url?q=https://pansionat-rnd.ru/ http://cse.google.ps/url?q=https://pansionat-rnd.ru/ http://www.google.co.il/url?q=https://pansionat-rnd.ru/ http://www.google.com.hk/url?q=https://pansionat-rnd.ru/

  7. Very nice depth 😮
    ?Cialis funciona! Y si, ?esta clinicamente probado!
    Ya lo dijimos, pero vale la pena volver a mencionarlo, Cialis es la unica pastilla para la disfuncion erectil clinicamente probada que funciona hasta 36 horas. Este medicamento ya ha Cialis sido sometido a multiples investigaciones clinicas que demostraron su capacidad para ayudar a mejorar la ereccion de los pacientes en un estudio controlado mediante placebo. El resultado fue que en un universo de mas de 700 pacientes, el 88% informo una mejora significativa en su ereccion.

    I favor the viewpoint!
    https://comprarcialis5mg.org/cialis-5-mg-precio/
    ?Todos pueden tomar Cialis?
    Siempre debe consultar con su medico primero, pero podemos decir de antemano que las personas que usan nitratos (nitroglicer) o bloqueadores alfa no deben tomar Cialis.
    https://sites.google.com/view/pin-upcasino/

Leave a Reply

Your email address will not be published. Required fields are marked *