html - 如何在div中定位元素

标签 html css position css-position

我正在学习如何制作网站。

这是我的正文标签:

<body>
    <h1 id="title">Title</h1>

    <div id="loginContainer">

        <img id="usernameIcon" src="assets/images/usernameIcon.png" alt="">
        <input id="usernameInput" type="text">

        <img id="passwordIcon" src="assets/images/passwordIcon.png" alt="">
        <input id="passwordInput" type="password">

        <button id="loginButton">Sign in</button>
    </div>
</body>

CSS文件:

#title {
    color: black;
    text-align: center;
    letter-spacing: 1px;
    font-weight: bold;
}

#loginContainer{
    width: 60%;
    height: 400px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 80px;
    background-color: white;
    border-radius: 20px;
    box-shadow: 10px 10px 72px -26px rgba(0,0,0,0.75);
}

#usernameIcon{
    width: 30px;
    height: 30px;
    margin-top: 70px;
    margin-left: 30%;
}

#usernameInput{
    width: 30%;
    height: 30px;
}

#passwordInput{
    width: 30%;
    height: 30px;
}    

#passwordInput:focus-within{

}

#passwordIcon{
    width: 30px;
    height: 30px;
}

#loginButton{
    width: 40%;
    height: 40px;
    border-radius: 15px;
    border-width: 0;
    background-color: green;
    margin-top: 230px;
    margin-left: 30%;
    margin-right: 30%;
}

我制作了网站模板:Template

上面的代码将我的网站设计成这样:First image

当我在 CSS 文件的 #passwordInput 中添加 margin-top: 150px; 时,我的网站看起来像这样:Second image

为什么所有 UI 元素都改变了位置? 我只在 #passwordInput 中添加了 margin-top: 150px;

我正在学习如何制作和设计网站。 敬请谅解。

最佳答案

因为所有元素都在同一个 div 中,当您给其中一个元素留出边距时,它会展开。

而是给它 position: relativetop: 150px

#passwordInput {
  position: relative;
  top: 150px;
}

关于html - 如何在div中定位元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56043867/

相关文章:

html - 需要以两行显示 ng-option Angular 6

javascript - 动态创建的列表上的单击事件

html - 如何制作自定义形状的 div,或操作 div

javascript - Twitter Bootstrap 的响应式设计

css - IE9 与 Opera、Firefox 与 Opera 的 CSS 定位差异

javascript - 在列表容器内单击时查找列表中的两个周围元素

javascript - 从显示 :none to display:block? 向下滑动动画

javascript - 浏览器如何在大声朗读时突出显示单词/句子?

javascript - 如何将 javascript 设置样式属性返回到 CSS 默认值

WPF 分隔符位置