user1457366
user1457366

Reputation: 669

Can I put a border around an html element that won't be affected by padding/margin?

The situation: I have an image that has a 15px padding on the right and I need to put a border or outline around the image. The problem is that both border and outline will be placed on the outer edge of paddings, creating a gap. Is there a method to add a border or outline that will ignore the padding and hug the image itself?

Example

HTML:

<div class="">
    <img class="" src="http://www.emoticonswallpapers.com/avatar/art/TV-Test-Card.jpg" alt="">
</div>

CSS:

div {
    position: relative;
    width: 50%;
}
img {
    position: absolute;
    width: 100%;
    padding-right: 15px;
    outline: 1px solid #000;
}

Upvotes: 4

Views: 14207

Answers (4)

lyxal
lyxal

Reputation: 1118

It seems that replacing padding-right with margin-right doesn't affect the border on the image, as shown in this JSFiddle.

So the CSS becomes:

div {
    position: relative;
    width: 50%;
}
img {
    position: absolute;
    width: 100%;
    margin-right: 15px; /*Changed from padding-right*/
    outline: 1px solid #000;
}

Just leaving this answer here in case anyone in the future needs a quick and easy fix.

Upvotes: -1

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201588

No, because when you use border or outline, the lines are drawn by CSS definitions so that the padding is inside.

So you need to consider replacing padding by something else. There are several possible approaches, and their feasibility depends on the context that was not disclosed in the question. One approach is to use positioning, especially sence you are using it anyway: replace padding-right: 15px by the following:

left: 0;
right: 15px;

Upvotes: 0

Armando Esta&#241;ol
Armando Esta&#241;ol

Reputation: 61

Try wrapping it:

HTML

<div class="some">
    <div class="other">
    <img class="image" src="http://www.emoticonswallpapers.com/avatar/art/TV-Test-Card.jpg" alt="" />
    </div>
</div>

CSS

.some {
    position: relative;
    width: 50%;
    background:#FEF;
}
img {
    position: absolute;
    width: 100%;

    outline: 1px solid #000;
}
.other {
    padding-right: 15px;
}

That way you will control both separately.

Upvotes: 1

sanepete
sanepete

Reputation: 1120

This does it, unless you are trying to cut down on div tags.

<div class="outerawesomediv">
  <div class="innerawesomediv">
    <img class="" src="http://www.emoticonswallpapers.com/avatar/art/TV-Test-Card.jpg" alt="">
  </div>
</div>

.outerawesomediv
{
 position:relative;
 width:50%;
}
.innerawesomediv
{
 padding-right:15px;
}
img
{
 position:absolute;
 width:100%;
 outline:1px solid #000000;
}

Upvotes: 1

Related Questions