Sophia111
Sophia111

Reputation: 167

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>

Upvotes: 1

Views: 14759

Answers (3)

Moob
Moob

Reputation: 16184

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>

Upvotes: 1

Pranjal
Pranjal

Reputation: 1118

Remove position: absolute and make margin-left:auto; Such that:

.arrow {
  background-color:#ECEFF5;
  width: 30px;
  margin-top: -12px;
  margin-left: auto;
}

Upvotes: 1

&#214;zg&#252;r Ersil
&#214;zg&#252;r Ersil

Reputation: 7013

try with %50 margin-left and - width/2 left position to centre

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

Upvotes: 1

Related Questions