Ask Your Question
2

How can I create a transition on click using CSS without the need for JavaScript?

asked 2022-04-01 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-11-21 19:00:00 +0000

lakamha gravatar image

You can use the :target pseudo-class in CSS to create a transition on click without the need for JavaScript. Here's an example:

HTML:

<div class="box">
  <a href="#clicked">Click me</a>
  <div class="content" id="clicked">
    <p>Some content here</p>
  </div>
</div>

CSS:

.box {
  position: relative;
  width: 200px;
  height: 200px;
}

.content {
  position: absolute;
  top: 0;
  left: 100%;
  width: 200px;
  height: 200px;
  background-color: #f00;
  transition: transform 0.5s ease-in-out;
  transform: translateX(-100%);
}

.content:target {
  transform: translateX(0);
}

a {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

In this example, we use the :target pseudo-class to target the clicked element with the id of "clicked". We also use the transition property to set the duration and easing of the transition between the two states. Finally, we use the transform property to move the content div from the left side of the box to the right side.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-01 11:00:00 +0000

Seen: 10 times

Last updated: Nov 21 '22