html - CSS - 将图像与两个 div 对齐的正确方法

标签 html css

这一定是非常基础的,但它一直让我费尽心思。 这是我要实现的目标的基本图像

enter image description here

我有一个宽度为 100% 的容器 div。 我有一段文字,我把它放在一个段落标签下面,下面是一些输入字段和一个按钮。所有这些都应该居中。 我有一张图片,它应该位于文本和字段的右侧,并且与这两个 div 的高度大致相同。

当视口(viewport)变大时,图像应保持锚定在文本和输入字段的末尾 - 大约 20 像素的距离。如果我以 % 宽度 float 容器,它会随着窗口大小的增加而继续漂移吗?

我尝试了以下方法:

  • 一个用于容器的外部 div 和两个内部 div,一个向左浮动(包含文本和输入),另一个向右浮动(包含图像)
  • 一个外部容器,内部有 3 个独立的 div,1 个用于文本行,宽度为 100%,然后另一个用于输入字段,宽度为 70%,最终的 div 宽度为图像的 30%。
  • 一个容器,里面有一个 div。段落内的文本和图像并手动定位图像,然后是输入字段。

和许多其他类似的变体,但不知何故我仍然无法得到我正在寻找的东西。

正确的做法是什么?它看起来很简单,但经过几个小时的摆弄后,我仍然无法理解。 请记住,此代码将存在于响应式模板中,因此我不希望使用固定值或定位。一旦调整到移动断点,我将需要重新设置输入的样式以与右侧的图像堆叠在一起(但我认为目前这无关紧要)。

对于这项让我感到越来越愚蠢的任务,非常感谢任何帮助!我一定错过了一些相当基本的东西.. 这是一个 fiddle 示例,任何人都可以随意编辑。 Fiddle

.inner {
    margin: 0 auto;
    text-align:center;
    padding-bottom: 10px;
}

.container {
    width: 100%;
    background-color:beige;
}

.myImage {
    padding-top: 10px;
}
<div class="container">
  <div class="inner">
    <p class="textSignup">
      Get the latest tips on an interesting subject and a FREE extract from our Guide
      <img class="myImage" src="http://www.vapld.info/images/ys/books.png" width="100" height="65">
    </p>

    <input type="text" name="FNAME" placeholder="Your first name" id="firstName">
    <input type="email" name="EMAIL" size="11" placeholder="Your email" required="">
    <input type="submit" value="Download my free ebook">
  </div>
</div>

最佳答案

你可以做什么:

  • 将你的 .myImage float 到右边
  • 添加 clearfix.inner

演示

.inner {
    margin: 0 auto;
    text-align:center;
    padding-bottom: 10px;
    max-width: 560px;
}
  
.inner:before,.inner:after {
    content: "";
    display: table;
}

.inner:after {
    clear: both;
}

.container {
    width: 100%;
    background-color:beige;
}
  
.textSignup {
    padding-bottom : 15px;
}

.myImage {
   padding-top: 10px;
   float:right;
}
<div class="container">
  <div class="inner">
    <p class="textSignup">
      Get the latest tips on an interesting subject and a FREE extract from our Guide
      <img class="myImage" src="http://www.vapld.info/images/ys/books.png" width="100" height="65">
    </p>

    <input type="text" name="FNAME" placeholder="Your first name" id="firstName">
    <input type="email" name="EMAIL" size="11" placeholder="Your email" required="">
    <input type="submit" value="Download my free ebook">
  </div>
</div>

(另见 this Fiddle)

关于html - CSS - 将图像与两个 div 对齐的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36178931/

相关文章:

javascript - 动态更改指向箭头以指向点击源

html - 下拉菜单在 IE8 中消失

html - 表格中的两列

html - 如何将一张图片放在左边,另一张图片放在一行的中央?

css - 我的 div 无法正确对齐。为什么?

jquery - 图像未在 HTML 页面的 jQuery load() 中加载

javascript - 将 google 脚本对象传递给 html 模板

html - 为什么我的右侧栏的第一个 div 表现得很奇怪?(我的所有样式都相同)

javascript - 如何在 Bootstrap Material 设计的输入文本中制作标签支持?

css - 响应式 "background-image"不会随着方向更改 css iOS 自动调整大小