Mohsen
Mohsen

Reputation: 332

CSS: Image appears outside div borders

I am trying to create a div containing an image on the left and other contents such as text on the center. When I add a border to the div, the image appears to be outside.

enter image description here

  <div style="padding: 20px;">
  <div style="border: solid black 2px">
    <img width="100px" height="150px" style="float: left;" src="https://karateinthewoodlands.com/wp-content/uploads/2017/09/default-user-image.png">
    <p>Username</p>
    <p>User Role</p>
  </div>
</div>

Is it because of the float property?

Upvotes: 0

Views: 1794

Answers (4)

Anjali Rawat
Anjali Rawat

Reputation: 66

Yes, it is because of float property. What you can do is

<div style="border: solid black 2px; overflow:hidden;">
  <img width="100px" style="height:auto;float: left;margin-right: 10px;" src="https://karateinthewoodlands.com/wp-content/uploads/2017/09/default-user-image.png">
  <p>Username</p>
  <p>User Role</p>
</div>

You need to give the parent div Overflow: hidden; property and remove the height of the image. You should not fix the height of the image, instead, you should give a max-height property that will prevent an image to go beyond the max-height. Also I have added height:auto;margin-right: 10px; to the img tag which you can edit or remove if not needed.

Upvotes: 0

Amini
Amini

Reputation: 1792

Yes, it's because of the float. Float is not recommended anymore because of these issues sometimes. You can fix it using overflow: auto or clear: both in the container to fix this problem.

<div style="padding: 20px;">
  <div style="border: solid black 2px; overflow: auto">
    <img width="100px" height="150px" style="float: left;" src="https://karateinthewoodlands.com/wp-content/uploads/2017/09/default-user-image.png">
    <p>Username</p>
    <p>User Role</p>
  </div>
</div>

Upvotes: 0

m_j_alkarkhi
m_j_alkarkhi

Reputation: 367

I'd avoid float. Use flex instead

<div style="padding: 20px;">
  <div style="border: solid black 2px; display: flex;">
    <img width="100px" height="150px" src="https://karateinthewoodlands.com/wp-content/uploads/2017/09/default-user-image.png">
    <div>
        <p>Username</p>
        <p>User Role</p>
    </div>
  </div>
</div>

Upvotes: 0

Kokodoko
Kokodoko

Reputation: 28158

If you use flex instead of float the div will stay in the same size as the image.

  <div style="padding: 20px;">
  <div style="border: solid black 2px; display:flex">
    <img width="100px" height="150px" src="https://karateinthewoodlands.com/wp-content/uploads/2017/09/default-user-image.png">
    <div>
      <p>Username</p>
      <p>User Role</p>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions