left align images breaks ul block

1.6k Views Asked by At

Aligning the image(400x100) left breaks the ul block: some items are on the right side of the image, some items are under the image. How to make the ul block stay together? i.e. all items are on the right side of the image. Also the image overlaps with the ul block.

<img src="url" align="left">

<div>
  <ul>
    <li>Hello</li>
    <li>Hello</li>
    <li>Hello</li>
    <li>Hello</li>
    <li>Hello</li>
    <li>Hello</li>
    <li>Hello</li>
  </ul>
</div>

3

There are 3 best solutions below

2
kzhao14 On BEST ANSWER

Simply add a display: inline-block; to your <ul>. This sets the <ul> to be displayed in the same line as the image, thus keeping it together as follows:

img {
  width: 400px;
  height: 100px;
}
ul {
  display: inline-block;
}
<img src="url" align="left">

<div>
<ul>
<li>Hello</li>
<li>Hello</li>
<li>Hello</li>
<li>Hello</li>
<li>Hello</li>
<li>Hello</li>
<li>Hello</li>
</ul>
</div>

0
greatgumz On

First thing you should do is remove the align="left" attribute from your img element as all elements are left aligned by default and the align attribute is typically only reserved for the table element by default. The img and div elements have the display: block; attribute by default. There are two decent solutions for your problem.

1. Float the two elements and don't forget to clear your floats. You should also get in the habit of indenting properly so you can see the parent child relationship in your HTML structure.

HTML

    <div class="container">
      <img src="#">
      <div>
        <ul>
          <li>Hello</li>
          <li>Hello</li>
          <li>Hello</li>
          <li>Hello</li>
          <li>Hello</li>
          <li>Hello</li>
          <li>Hello</li>
        </ul>
      </div>
    </div>

CSS

    img,
    div {
        float: left;
    }

    .container {
        overflow: hidden;
    }

2. Set both elements to be inline-block elements.

CSS

    img,
    div { 
        display: inline-block;
    }
0
Johannes On

In your particular case:

ul {
  clear: left;
}

(if you want the ul below the image)

http://codepen.io/anon/pen/xRENMB

(But you should use a class for the ul and the rule, so that other uls won't be affected)