填充不适用于我的文本

时间:2014-10-14 10:29:17

标签: html css

HTML:

<div id="main">
<div style="position: absolute; height: 150px; width: 400px; left: 290px;"><img src="HEAD-IMAGE.jpg" /></div>
<div style="position: absolute; height: 300px; width: 233px; top: 180px;"><img src="LEFT-IMAGE.jpg" />(below head)</div>
<div style="position: absolute; top: 200px; left: 270px;">TEXT (next to left image)</div>
</div>

的CSS:

div#main{
 position: absolute;
 top: 141px; left: 50%;
 height: 100%; width: 960px;
 padding: 10px;
 margin-left: -490px;
 text-align: justify;
 background-color: yellow;
}

来自#main的填充适用于我的图片,但不适用于我的文字(右侧和底部填充)。

4 个答案:

答案 0 :(得分:1)

为什么会这样?

在您的示例中,只有文本div具有topleft属性。包含图像的两个div仅包含以下属性之一:

  • 标题div有left: 290px;,因此它的y轴位置会被顶部填充移动。

  • 左边的div有top: 180px;,所以它的左侧填充移动了x轴位置。

  • 文本div有top: 200px; left: 270px;,因此其x和y轴不受填充的影响。

为了说明这一点,对于此示例,文本div已删除其left属性。它现在受到其容器左侧填充的影响:

(&#34;显示代码段&#34;并运行它)

&#13;
&#13;
#main {
  position: absolute;
  top: 141px;
  left: 50%;
  height: 100%;
  width: 960px;
  padding: 50px;
  margin-left: -290px;
  text-align: justify;
  background-color: yellow;
}
.header {
  position: absolute;
  height: 150px;
  width: 400px;
  left: 290px;
  background: #F00;
}
.left {
  position: absolute;
  height: 300px;
  width: 233px;
  top: 180px;
  background: #F00;
}
.text {
  position: absolute;
  top: 200px;
  background: #F00;
}
&#13;
<div id="main">
  <div class="header">
    <img src="http://www.placehold.it/200" />
  </div>
  <div class="left">
    <img src="http://www.placehold.it/200" />
  </div>
  <div class="text">You can't handle the truth, soldier!</div>
</div>
&#13;
&#13;
&#13;

位置:绝对是布置元素的最佳方式吗?

取决于... position: absolute从文档的正常流程中删除元素。也就是说,每个元素对另一个元素基本上是不可见的。如果您希望创建灵活的布局,则可能会出现问题,布局可根据用户浏览器的高度/宽度重新调整大小。

您能告诉我另一种布局HTML元素的方法吗?

当然!有很多方法可以将页面布置为{/>>来使用position: absolute。以下是使用display: flex的基本示例 - 布局元素的更新方法。它还没有100%的浏览器支持,所以这纯粹是一种技术的例子:)

了解更多:

Flex示例

注意当示例全屏显示时元素的大小调整。

&#13;
&#13;
* {
  margin: 0;
  padding: 0;
}
body {
  width: 80vw;
  max-width: 800px;
  margin: 0 auto;
  background: #424242;
}
header {
  background: #e91e63;
  height: 20vh;
}
.wrap {
  display: flex;
}
.left {
  background: #fce4ec;
  flex: 1;
}
.content {
  background: #fafafa;
  min-height: 70vh;
  flex: 2;
}
footer {
  height: 10vh;
  background: #c51162;
}
&#13;
<header>
  I am header
</header>
<div class="wrap">
  <div class="left">
    I am sidebar
  </div>

  <div class="content">
    I am content
  </div>
</div>
<footer>
  I am footer, hear me roar! RWAR!
</footer>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

.child

定义课程<div>
<div class="child">

并相应地定义样式

.child { padding: 10px; }

答案 2 :(得分:0)

在子div上使用position: relative;使其成为父div填充的帐号。

答案 3 :(得分:0)

问题是你给文本div左边和顶部,为什么不接受填充,只需删除左边的文本div然后它将接受填充...