Sophia111 Sophia111 - 4 months ago 51
CSS Question

How to set max margin-left?

I have a webpage with responsive design, whose body I have set to max-width: 500px; and a div 'arrow' whose margin-left:45%. When screen size goes beyond 500px, the body stays fine and fixed, but since the div arrow's margin-left is 45% of screen size, it starts moving in the wrong direction.

Is there a way to set a max on margin-left so that arrow div doesn't move beyond a point even if screen-size keeps increasing?
CSS Code is below:

.arrow {
background-color:#ECEFF5;
width: 30px;
margin-top: -12px;
position: absolute;
margin-left: 45%;
}

html, body {
margin: 0 auto;
}

body {
background-color: #ECEFF5;
font-weight: lighter;
max-width: 500px;
}


And HTML is:

<body>
<div class="userdata">
<h2 style="font-weight:bold;"> First Name</h2>
<input class="input" type="text" name="firstname">

</div>
<div class="arrow">
<img src="arrow.png" style="position:absolute; width: 30px;">
</div>
<div class="instructions" id="test">
<h5>Step 1/7</h5>
<hr width="100%">
<h6 >Write your name here</h6>
<a href="xyz.html" class="button-nav" > Back </a>
</div>

Answer

Add position:relative; to the body. Then the margin will be 45% of the body rather than the window.

Eg:

.arrow {
  background-color: red;
  width: 30px;
  margin-top: -12px;
  position: absolute;
  /* margin-left: 45%; */
  left: 45%; /* <- why not just position left rather than using a margin? */
}
html, body {
  margin: 0 auto;
  height: 100%; /* <-just for demo */
}
body {
  background-color: #ECEFF5;
  font-weight: lighter;
  max-width: 500px;
  border: 1px solid red; /* <-just for demo */
  position: relative;  /* <- make relative */
}
<div class="arrow">arrow</div>

Comments