简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM