Robin
Robin

Reputation: 61

Cut margin-left of element in half under certain window width

I want to cut the margin-left of a div container in half under a certain window width (mobile).

I've tried this with parseInt, .css and store it temporarly in a variable. Then cut it in half and use .replace.

if ($(window).width() <= 590) {
    let oldmargin = parseInt($("#div").css("marginLeft"));
    let newmargin = oldmargin/2;
    $("#div").css("marginLeft").replace('rem', newmargin);
  }

Unfortunately the code is not working.

Upvotes: 0

Views: 206

Answers (1)

To set a new value of margin-left, try with $("#div").css("margin-left",newmargin);

To GET a value using .css() = $("#div").css("margin-left")
To SET a value using .css() = $("#div").css("margin-left",newmargin)

$('.div').each(function() {
  var oldmargin = parseInt($(this).css("marginLeft"));
  var newmargin = oldmargin / 2;
  $(this).css("marginLeft", newmargin);
});

Demo

$('.div').each(function() {
  var oldmargin = parseInt($(this).css("marginLeft"));
  var newmargin = oldmargin / 2;
  $(this).css("marginLeft", newmargin);
});
.div {
  margin-left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div">#div</div>
<div class="div">#div</div>

Upvotes: 1

Related Questions