html - 使用 :hover while it's expanding width 正确居中元素

标签 html css

当您将焦点或悬停在输入上时,我希望将输入完全居中。

因此我希望它在中间而不是在右边扩展宽度或使其看起来像它的东西。

代码:

.container {
   margin-top: 10px;
   margin-left: auto;
   margin-right: auto;
   width: 142px;
}

.textbox { 
   border: 1px solid #848484; 
   outline: 0; 
   height: 25px; 
   width: 125px; 
   padding: 2px 20px 2px 20px;
  }
  
input { 
   text-align: center;
   width: 100px;
   transition: ease-in-out, width .35s ease-in-out;
   margin-bottom: 3px;
   margin-top: 3px;
}

input:hover, input:focus { 
   width: 150px;
   margin-bottom: 3px;
   margin-top: 3px;
}
<div class="container">
   <input type="text" class="textbox" placeholder="Some text in here!">
</div>

最佳答案

您遇到的问题是由 .container 的固定宽度值引起的,该值小于您在 :hover 上应用到输入的宽度。

消除固定宽度并应用 text-align: center 属性(使输入居中)会导致悬停效果按预期运行

.container {
	margin-top: 50px;
	margin-left: auto;
	margin-right: auto;
	text-align: center;
}

.textbox { 
   border: 1px solid #848484; 
   -moz-border-radius-topleft: 30px;
   -webkit-border-top-left-radius: 30px;
   border-top-left-radius: 30px;
   -moz-border-radius-topright: 30px;
   -webkit-border-top-right-radius: 30px;
   border-top-right-radius: 30px;
   outline: 0; 
   height: 25px; 
   width: 125px; 
   padding: 2px 20px 2px 20px;
  }
  
input { 
   text-align: center;
   width: 100px;
   transition: ease-in-out, width .35s ease-in-out;
   margin-bottom: 3px;
   margin-top: 3px;
}

input:focus { 
   width: 150px;
   margin-bottom: 3px;
   margin-top: 3px;
}

input:hover { 
   width: 150px;
   margin-bottom: 3px;
   margin-top: 3px;
}

/* Ignore this */

p {
  margin-top: 30px;
  color: #a6a6a6;
  text-align: center;
}
<!-- Thanks for helping :p !-->

<div class="container">
   <input type="text" class="textbox" placeholder="Some text in here!">
</div>

<!-- Ignore !-->
<p> So as you can see the width will expand to the right, how would I be able to center it while it's moving and keeping it centered?</p>

关于html - 使用 :hover while it's expanding width 正确居中元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39317138/

相关文章:

jquery - 如何使用 ajax 发布包含动态表中的字段的表单,可以为其动态添加行和列

javascript - 如何将 child 的div高度扩展到 parent 的高度

html - 使用固定 DIV 时禁用 Firefox 抗锯齿

css - '位置: static ;' vs ' position: relative;' when child element is absolutely positioned

html - 特定尺寸的 CSS Hover

jquery - 表格的条件格式

html - MSHTML 解析 ARTICLE 标签无效

html - 在宽度受限的父元素内水平居中没有设置宽度的子元素

css - Bootstrap 4 超大屏幕列的排序 - order-xs- 不工作

javascript - jquery 样式在 react 组件中不起作用