Roll overs in html

Простой ролловер на CSS

Возвращаясь к теме ролловеров, хочу показать простейший из его примеров. Напомню, что ролловером в верстке называется картинка, которая меняется при наведении на нее указателя мыши. Для работы данного эффекта необходимо использовать известное свойство ссылки под названием hover.

А как быть, если нам, к примеру, нужно сделать лишь саму картинку в виде ссылки, но без всякого текста. Например, лого. Есть красивый рисунок, и нам вовсе ни к чему на нем сверху накладывать текст ссылки. А делать «пустую» ссылку валидатор не позволяет.

Для решения этой задачи можно применить свойство текста, называемое text-indent, которое обычно применяется для «красной строки». Но только задать ему отрицательное значение, причем достаточно большое. Тогда текст будет прятаться далеко за границей страницы сайта. Таким способом поступают довольно часто, особенно при использовании рисованных логотипов.

Но вернемся к нашим баранам, сиречь ролловеру. Принцип работы такой меняющейся картинки весьма прост: рисуется двойное изображение, одно строго под другим:

Как видно из рисунка, высота общей картинки должна быть четной и составлять сумму высот обоих изображений: 256+256=512px.

Далее в файле стилей мы задаем класс для будущей ссылки, которая по-сути и будет выполнять роль ролловера. Здесь есть несколько хотростей. Во-первых, класс задается не просто именем с точкой впереди, а приписывается непосредственно к тэгу а:

Читайте также:  Enable php errors in apache

Во-вторых, мы используем картинку не напрямую (как через тэг img), а исключительно в качестве фона. Но! Так как у нас картинка одна общая, то нам нужно вначале каким-то образом показывать ее не всю, а лишь верхнюю часть. Для этого указанному выше классу зададим следующий набор правил:

a.picture background: url(santa.gif) no-repeat 0 0;
width: 256px;
height: 256px;
display:block;
text-indent: -1000em;
>

Как видите, в качестве бэкграунда мы прописали название самой картинки, без повтора, но с координатами 0 0.

Вот как раз эти самые координаты и сообщают браузеру, что показывать нужно картинку, начиная с ее левого верхнего угла. Но до каких пор? А вот как раз до 256px по ширине и столько же по высоте. И не более того.

Кроме того, чтобы все это дело верно работало, следует прописать правило отображения display:block;

Текст, как я уже говорил, нам нужно спрятать. Поэтому мы добавили такое правило: text-indent: -1000em; Этого значения с лихвой хватит, даже если у вас будет монитор с диагональю в 5 метров.

Но это лишь половина дела. Как же нам показать вторую часть картинки? Для этого добавим следующий очень короткий набор правил:

a.picture:hover background: url(santa.gif) no-repeat 0 -256px;
>

Вуаля! Все просто как 2х2. Используя все ту же картинку в качестве фона, мы для свойства hover изменили лишь координаты данного рисунка. По ширине как был ноль, так он и остался, а вот высоту мы задали с отрицательным значением ровно на половину картинки. Тем самым мы как бы спрятали верхнюю его часть и показали нижнюю. Вот и все.

Живой пример можно посмотреть здесь

Источник

Rollover Image Effect in Html

code explanation for Rollover Image Effect in Html

Output for Rollover Image Effect in Html

  1. The output image while the page loads.

Output for Rollover Image Effect in Html

When user try to mouse over to the image then the image will be changed.

Browser Support for Rollover Image Effect in Html

Yes Yes Yes Yes Yes

Rollover Image Effect in Html rollover image html rollover image css rollover image html w3schools divi image hover rollover image dreamweaver rollover image example divi image module hover divi image text overlay rollover image effect in html rollover image rollover image html html rollover image css rollover image rollover image css rollover image effect css rollover image gallery rollover image code html rollover image code create rollover image rollover image html code css rollover image effects html5 rollover image what is a rollover image wordpress rollover image

    INTERVIEW TIPS
  • Final Year Projects
  • HR Interview Q&A
  • GD Interview
  • Resume Samples
  • Engineering
  • Aptitude
  • Reasoning
  • Company Questions
  • Country wise visa
  • Interview Dress Code CAREER GUIDANCE
  • Entrance Exam
  • Colleges
  • Admission Alerts
  • ScholarShip
  • Education Loans
  • Letters
  • Learn Languages

World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.

Источник

Rollovers

If you want to add rollovers (buttons or images that change when you move the mouse over them) to your web-page, don’t use a wizard, or Fireworks, to add them — have a go at making them yourself. They’re surprisingly easy!

The first thing you need to do, if you’re using a program such as Dreamweaver or Expression Web, is make sure that you can see the code for your web-page. Both applications have a setting that allows you to see both your page and the code that makes it. If you’re using a program, such as Serif WebPlus, that doesn’t allow you to see the code, then you really need to switch to something else before you can learn how to create web-pages properly.

Basic Idea

The basic idea is that you create two styles for your buttons, and you swap between them as the mouse moves over. This used to require programming, and something called JavaScript, but it’s now much easier using a thing called CSS (Cascading Style Sheets).

CSS is what programs like Dreamweaver use to style text, buttons and images, and you can have two styles for the same thing — one for the object as it’s normally displayed, and one for the object as you want it to appear when the mouse is moved over it. You don’t need any code to swap between the two; the browser does it automatically.

It’s important that you choose the two styles carefully so that the elements don’t change size when the mouse moves over them — that can cause text-wrapping to change, or for things to be pushed up or down the page as the mouse moves around, which looks messy and harms readability.

Simple Example

Look at the rectangle on the right — it’s something called a «div», created with the tag in HTML. It’s like the web-page equivalent of a text-box. I’ve used a div, but you could use the same technique with a button or even just a hyperlink. In the code for this page, I’ve called the button button1, and I’ve added the following style definitions:

What this does is give button1 a foreground colour of red and a background colour of yellow, but when the mouse hovers over it, the two colours are reversed. Move your mouse over the button and see what it does. That’s with no JavaScript and no programming. Notice also that no graphics are required — CSS allows to create plain coloured buttons, or even buttons with gradient colours, without using a background image.

Using More Attributes

Actually, the basic principle is the same — two different styles that we swap between — it’s just that the styles are more complex. I’m sure you can create a better-looking button than this, but here are the styles for this button:

Notice that with CSS, you only need the :hover style to say what has changed when the mouse moves over — the font is still white and the corners are still rounded (border-radius rounds the corners, but only works with newer browsers) even though #button2:hover doesn’t set the font color or border radius. Notice also that because the border gets thicker, that makes the button get bigger, so we need to reduce the size of the margin to stop everything shifting down and across the page.

Using Transitions

Transitions and transformations are an exciting new addition in CSS3 and you can read more about them on the animations page. Here I have combined them with the :hover selector to produce an effect that you might want to use sparingly!

The circle is a with border-radius set to 50% to round off the corners. It also has the CSS attribute transition: all 1s, which means that any changes applied to it will happen gradually over a period of 1 second — any new colours will fade in, and changing the angle will make the element rotate into position. The :hover style simply inverts the foreground and background colours and uses transform: rotate(360deg) to effect the rotation.

Is That It?

Pretty much, although if you look at the source for this document, you’ll notice an extra style:

What that style does is give both buttons a size, sets the font to one that looks like Arial, and positions the button on the right of the screen — you probably won’t need that in a page that you’re creating, I just added that because I wanted to put my example buttons next to the text.

You might have noticed that some style names begin with a #, some with a ., and it’s also possible to have nothing at the start. What’s the difference?

Style names with no prefix apply to all HTML elements with that name, e.g.

would make all paragraphs have a font of size 24 pixels.

Style names that begin with a . apply to elements with that class name, so that .example style above applies to both buttons because they both have a class of example, e.g.

Finally, styles beginning with a # apply to elements with that id, so style #button1 only applies to the element with id="button1". This means that styles beginning with a # should can only be applied to one thing on the page, whereas styles beginning with . can be applied to many. In the case of button1 above, the browser will try to apply all the styles from both #button1 and .example.

Problems?

Only users who have a mouse will get to see your rollover! A few years ago, that wasn’t a problem, because everyone using the world-wide web was using a computer. Now, however, you have to consider that visitors to your site might be using a phone, tablet, or other touch-screen device.

Источник

Rollovers

HTML Dog

Rollovers are a fine old tradition in web design. They basically involve changing one thing to another thing when the cursor hovers over it. If you use an image for a link, for example, you could swap that image with another one when it is hovered over. Here are some methods for achieving this goal, including some CSS3 effects that have expanded the possibilities of modern rollovers.

Image swapping

The earliest rollovers used JavaScript to swap one img element with another. Then CSS came along and, using :hover , we could more easily change a background image used in place of a text link. Cleaner, simpler, more semantic, and nice and accessible.

An obvious solution for achieving this would be to do something like this:

The link text is pushed out of the way, an image (“toucanfade.jpg”) is plonked in its place, and that image is swapped (with “toucan.jpg”) when the link is hovered over.

The trouble with this is that there will be a delay when the link is hovered over, as the image for the rollover downloads, making the effect far from instantaneous.

The way to get around this is to actually have just one image that comprises the two images you want, one on top of the other.

This image can be manipulated with the following CSS, which achieves the same result as the previous example, but because there is only one file involved, containing “two” images, everything necessary for the rollover is downloaded at once, making the effect instantaneous.

The technique can be extended further by accommodating other link states such as active and having an image file with additional portions.

If you attempt to use transitions with this method you might not get the effect you desire. Because the image is essentially moving from one position to another, the transition will show the upward or downward movement, rather than a fade from one image to another.

Fade in / fade out

CSS won’t let you change the opacity of background images. If it did, you could apply two background images to a link and change the opacity of one from transparent to solid on hover. Accompanied by a cheeky transition this would achieve a smooth fade-in / fade-out effect.

We can, however, alter the opacity of a box containing a background image. So if we have two boxes, one on top of the other, we can achieve the same thing:

 #toucan < display: block; width: 200px; height: 63px; background: url(images/toucancombo.jpg); text-indent: -999em; position: relative; >a:after < content: ""; display: block; width: 200px; height: 63px; background: url(images/toucancombo.jpg) bottom; position: absolute; top: 0; opacity: 0; -webkit-transition: .5s; transition: .5s; >a:hover:after

Here we’re creating another area for styles to play with using :after , so leaving the HTML untouched. We’re placing this box on top of the link, filling it with the desired rollover image, hiding it, and setting our transition. Then, when the link is hovered over, this invisible box becomes visible. Bam. Rollover.

Other options

  • Pseudo Classes (CSS Intermediate Tutorial)
  • Background Images (CSS Intermediate Tutorial)
  • Transitions (CSS Advanced Tutorial)
  • Transformations (CSS Advanced Tutorial)

Examples

  • Rollovers 1: graphical links that change when the cursor moves over them using :hover
  • Rollovers 2: further interactive effects, utilising the :active pseudo class
  • Rollovers 3: fade in / fade out
  • Rollovers 4: rotating, using transform
  • Transitions: using border-radius
  • Transition timing functions: rollovers with different animation properties

References

Источник

Оцените статью