Move an element right when window width decreases using CSS

Viewed 4969

Default behavior

* {
  margin: 0;
}
html,
body {
  height: 100%;
}
div {
  width: 10rem;
  height: 10rem;
  background-color: #333;
  position: absolute;
  left: 25%;
}
<div></div>

When the window is resized the div remains 25% from the left edge of it's container.

enter image description here

Can we increase or give the illusion of the percentage value of the left property increasing as the window's width is decreased?

Edit: Is this possible without using 1000 media queries or JavaScript while keeping a smooth, consistent, un-jittery transition?

I've actually achieved this effect with pure CSS a long time ago but forgot how it was done. My code was kind of convoluted and used a lot of percentages for widths and absolute positioning. But I know it's possible. Looking for a CSS hack at the very least.

4 Answers

You may get something near what you're looking for by having the distance from the left being composed of negative-scalar + constant values, instead of just a positive-scalar:

@keyframes changeSize {
  0%   { width: 100%; left: 0%; }
  50%  { width: 30%; left: 35%; }
  100% { width: 100%; left: 0%; }
}

.container {
  position: fixed;
  width: 100%; height: 100%;
  left: 0%; top: 0%;
  box-shadow: inset 0 0 0 1px #000000;
  
  animation-name: changeSize;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-timing-function: ease-in-out;
}
.container > .box {
  position: absolute;
  width: 50px; height: 50px;
  background-color: #000000;
  top: 50%; margin-top: -25px;
  left: -20%; margin-left: 150px; /* here's the negative-scalar + constant! */
}
<div class="container">
    <div class="box"></div>
</div>

The scalar becomes more significant, percentage-wise, as the parent's size decreases.

Note that the animation is just for demonstration! :)

To some extent it's possible: You can use the right property instead of left and a calc value for it that contains a percentage higher than 100%, minus a relatively large fixed value. It's some trial and error to find a setting that's appropriate for your individual situation:

* {
  margin: 0;
}
html,
body {
  height: 100%;
}
div {
  width: 10rem;
  height: 10rem;
  background-color: #333;
  position: absolute;
  right: calc(140% - 500px);
}
<div></div>

Try using Media Query in CSS

Learn More About Media Query

Example Code:

<!DOCTYPE html>
<html>

<head>
    <style type="text/css">
* {
  margin: 0;
}
html,
body {
  height: 100%;
}
div {
  width: 10rem;
  height: 10rem;
  background-color: #333;
  position: absolute;
  left: 25%;
}
@media screen and (max-width: 600px) {
  div {
    left: 50%;
  }
}
    </style>
</head>

<body>
   <div></div>
</body>

</html>
Related