Open Playground
JS TutorialLesson #172

CSS Instead of JavaScript

In HTML-first development, CSS is often the second step after HTML.

In HTML-first development, CSS is often the second step after HTML.

Many visual effects can be created with CSS instead of JavaScript.

CSS can handle layouts, hover effects, transitions, animations, responsive design, and simple state changes.

Share

Hover Effects

The :hover selector can change an element when the mouse is over it.

Example

Example Code

html
Try it Yourself
button:hover {

  background-color:#059862;

}

 Hover Over Me

Transitions

CSS transitions can animate changes smoothly.

Example

Example Code

html
Try it Yourself
.box {

  width:100px;

  height:100px;

  background-color:#04AA6D;

  transition:width 0.5s;

}

.box:hover {

  width:200px;

}

Show and Hide Content

CSS can show and hide content using selectors.

This can be useful for simple menus and dropdowns.

Example

Example Code

html
Try it Yourself
.menu-content {

  display:none;

}

.menu:hover .menu-content {

  display:block;

}

  Menu

    [Link 1](#)

    [Link 2](#)

Responsive Layouts

CSS media queries can change the layout for different screen sizes.

This avoids the need for JavaScript-based layout changes.

Example

Example Code

html
Try it Yourself
.container {

  display:grid;

  grid-template-columns:1fr 1fr 1fr;

  gap:16px;

}

@media (max-width:600px) {

  .container {

    grid-template-columns:1fr;

  }

}

CSS Animations

CSS animations can create repeated movement without JavaScript.

Example

Example Code

html
Try it Yourself
.spinner {

  width:40px;

  height:40px;

  border:6px solid #ddd;

  border-top:6px solid #04AA6D;

  border-radius:50%;

  animation:spin 1s linear infinite;

}

@keyframes spin {

  to { transform:rotate(360deg); }

}

When CSS Is Enough

CSS is often enough when the change is visual.

Use CSS for colors, sizes, spacing, layout, motion, and simple visibility changes.

Use JavaScript when the page needs logic, data processing, storage, or communication with a server.

If the problem is visual, try CSS first.

Interactive Code Examples

JS Example 1

html
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 2

html
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 3

html
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 4

html
Try it Yourself
JavaScript syntax and algorithm demonstration.
<style>

.container {

  display:grid;

  grid-template-columns:1fr 1fr 1fr;

  gap:16px;

}



@media (max-width:600px) {

  .container {

    grid-template-columns:1fr;

  }

}

</style>

JS Example 5

html
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview: