简体   繁体   English

在Div CSS中对齐图像和文本

[英]Aligning an Image and text within a Div CSS

I am trying to align an image and text within a div so it looks like the following 我正在尝试在div对齐图像和文本,因此如下所示


IMAGE TEXT 图片文字


However when I get them aligned as such, the background colour of the div no longer appears. 但是,当我照原样对齐它们时, div的背景色不再出现。

Can anyone suggest what I am doing wrong? 谁能暗示我在做什么错?

HTML: HTML:

<div class="introduction">
    <div class="image">
        <img src="">
    </div>
    <div class="text">
        <p>Text</p>
        <p>Good luck!!</p>
    </div>
</div>

css: CSS:

.introduction {
    margin: 0 50px;
    padding: 20px;
    background-color: #FFFFFF;
    color: #000000;
    -moz-border-radius: 10px;
    border-radius: 10px;
}
.image {
    width: 30%;
    float: left;
}
.text {
    width: 70%;
    float: left;
}

Putting the two floats in there side by side makes the parent container's height effectively 0. You can put a div with a style="clear:both;" 并排放置两个浮点数将使父容器的高度有效为0。您可以将div放置为style =“ clear:both;”。 before the parent's closing tag and you will get your background back. 在父母的结束标记之前,您将获得背景。

<div class="introduction">
<div class="image">
    <img src="" />
</div>
<div class="text">
    <p>
    Text
    </p>
    <p>Good luck!!</p>
</div><div style="clear:both;"></div></div>

Something like this may achieve what you want: 这样的事情可能会实现您想要的:

<style>
    .introduction{
        margin:0px;
        padding:5px;
        background-color:orange;
    }

    .introduction img{
        float:left;
        padding:10px;
    }

    .introduction p{
        padding-left:50px;
        background-color:blue;
    }
</style>

<div class="introduction">
    <img src="img/can_25.png" />
    <p>Text</p>
    <p>Good Luck</p>
</div>

Since your p's aren't floated, they will hold your div open .. depending on the size of your image. 由于您的p不会浮动,因此它们将使div保持打开状态,具体取决于图片的大小。

I would suggest you 2 solutions: 我建议您2个解决方案:

1) If you want to your output look like this: 1)如果要输出,则如下所示:

IMAGE TEXT 
IMAGE TEXT
      TEXT

HTML: HTML:

<div class="whole">
    <img class="ib" src="myimg.png" alt="my img" />
    <p class="ib">my text my text my text my text my text my text my text is so short I will die alone</p>
</div>

CSS: CSS:

.ib{ display:inline-block;}
.whole{ vertical-align:top}

.ib img{width:30%; border:0;}
.ib p{width:70%;margin:0;padding:0;}

2) or like this: 2)或像这样:

IMAGE TEXT TEXT
TEXT TEXT

HTML: HTML:

<img src="myimg.png" alt="my img" class="leftimg" />
<p>my text my text my text is so short I will die alone</p>

CSS: CSS:

.leftimg {
   float:left; 
   margin-right:5px;
}

DEMO: http://jsfiddle.net/goodfriend/b66J8/37/ 演示: http : //jsfiddle.net/goodfriend/b66J8/37/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM