简体   繁体   中英

How do I make a css item position absolutely to the parent element?

I want to add a "view password" icon inside of an html input. To do that, I added the material icons font and used one of its components. I nested it inside of the input to allow me to position it according to the input. I set the positon property of the input as "relative" and the position property of the icon as "absolute," but somehow, it still positions absolutely relative to the whole page. How can i fix this?

 .auth-input { text-align: left; padding: 7px 10px; background-color: #f6f6f6; border: none; border-radius: 5px; font-size: 1.05em; width: 100%; position: relative; } i.material-icons { position: absolute; top: 0 }
 <input type="password" name="password" id="password-input" class="auth-input"> <i class="material-icons">visibility</i> </input>

You cannot have html inside an input. It is a self closing tag. You need to put both elements into a container.

 .auth-input { text-align: left; padding: 7px 10px; background-color: #f6f6f6; border: none; border-radius: 5px; font-size: 1.05em; width: 100%; position: relative; } .auth-input input { width: 100%; } i.material-icons { position: absolute; top: 0 }
 <div class="auth-input"> <i class="material-icons">visibility</i> <input type="password" name="password" id="password-input" /> </div>

Wrap the two. See demo https://codepen.io/yifanai/pen/MWyvJRE

 .password-input-group { position: relative; } .auth-input { text-align: left; padding: 7px 10px; background-color: #f6f6f6; border: none; border-radius: 5px; font-size: 1.05em; width: 100%; position: relative; } i.material-icons { position: absolute; top: 7px; right: 10px; }
 <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel=" stylesheet"> <div class="password-input-group"> <input type="password" name="password" id="password-input" class="auth-input" /> <i class="material-icons">visibility</i> </div>

结果

 .auth-input { text-align: left; padding: 7px 10px; background-color: #f6f6f6; border: none; border-radius: 5px; font-size: 1.05em; width: 100%; } .layout { position: relative; } i.material-icons { position: absolute; top: 0; right: 20px; z-index: 1; }
 <span class="layout"> <input type="password" name="password" id="password-input" class="auth-input"></input> <i class="material-icons">visibility</i> </span>

Input TAG not have child, try it.

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