marcman
marcman

Reputation: 3383

Adjust div position fluidly as window width changes

I have a div with multiple absolute-positioned divs within it. I would like the left position of these inner divs to move fluidly as the window is resized. An example of what I have so far can be seen here: https://jsfiddle.net/ewqmfa4d/.

How can I do this? I presume I'd use jQuery? Note that I'm not looking for media queries, but rather something that provides fluid movement as the width of the window changes.

Upvotes: 0

Views: 147

Answers (2)

Obsidian Age
Obsidian Age

Reputation: 42304

I'm still note sure quite what you're looking for, but in order to modify the text offset, what you're looking to do is make use of a combination of .resize(), .width() and .css().

First check the current offset of $('#text'). Note that you might think that you can do this with $('#text').css("left"), but you'll actually need to make use of .position().

On load, you'll need to check the current size of the window, so you can work out whether the window is getting larger or smaller (meaning you're shrinking or growing it when resizing). You can compare these values against those in .resize() to work out whether the window is now larger or smaller.

Finally, you can set the left offset of the #text element with $("#text").css("left", text_offset += 10). Note that you increase the offset when shrinking the window, and decrease the offset when enlarging the window.

Here's an example putting all this together:

var w = 0;
var text_offset = $('#text').position().left;

$(document).ready(function() {
  w = $(window).width();
});

$(window).resize(function() {
  if (w > $(window).width()) {
    $("#text").css("left", text_offset += 10);
  } else {
    $("#text").css("left", text_offset -= 10);
  }
  w = $(window).width();
});
.top {
  font: "Arial Bold";
  font-weight: bolder;
  height: 300px;
  background-color: #000000;
  position: relative;
  text-align: center;
}

.top div {
  position: absolute;
}

#text {
  color: #c9d35f;
  top: 100px;
  left: 150px;
}

#text2 {
  color: #fa48bc;
  top: 175px;
  left: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='top'>
  <div id="text">My text</div>
  <div id="text2">Other text</div>
</div>

I've also created a snippet showcasing this here.

Note that you'll need to play around with the offset values, probably using 1 in place of 10 (because you drag by a single pixel)!

Hope this helps! :)

Upvotes: 1

Robert Cooper
Robert Cooper

Reputation: 2240

You could use a percentage for the value of the left attribute. In your Fiddle example, you would have to change your two text selectors to have to following css declarations:

#text{
  color: #c9d35f;
  top: 100px;
  left: 15%;
}

#text2{
  color: #fa48bc;
  top: 175px;
  left: 30%;
}

Upvotes: 0

Related Questions