Connect with us

CSS

CSS: How to Add a Border to an Image

Spread the love

Adding a border to an image is a simple and effective way to enhance its appearance, highlight content, or match your site’s design style. CSS gives you full control over the border’s width, color, style, and radius.

In this blog post, you’ll learn:

  • ✅ How to add a border to an image using CSS
  • 🎨 How to style the border (color, thickness, style)
  • 🔲 How to add rounded corners or shadows
  • 🧪 Real-world examples

✅ 1. Basic CSS Border for an Image

Let’s start with a simple image in HTML:

✅ HTML:

<img src="images/photo.jpg" alt="Sample Photo" class="bordered-image">

✅ CSS:

.bordered-image {
  border: 2px solid #333;
}

This applies a solid black border around the image with a 2-pixel width.


🎨 2. Customize Border Color, Width, and Style

You can modify the border style using the following properties:

.bordered-image {
  border: 5px dashed #ff6600; /* dashed orange border */
}
Border PropertyExample Values
border-stylesolid, dashed, dotted, double, groove
border-width1px, 5px, 0.5em
border-colorColor name, hex, rgb

🔘 3. Add Rounded Corners to the Image

To make the image corners smooth or circular:

.rounded-image {
  border: 4px solid #007bff;
  border-radius: 10px;
}

🧿 Make it Circular:

.circle-image {
  border: 3px solid #555;
  border-radius: 50%;
}

✅ Works best when the image has equal height and width.


🌟 4. Add Box Shadow with Border

For extra style and depth, add a shadow:

.shadowed-image {
  border: 2px solid #ccc;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

✅ Gives a subtle 3D or elevated look to the image.


🧪 5. Full Example

✅ HTML:

<img src="images/landscape.jpg" alt="Landscape" class="styled-image">

✅ CSS:

.styled-image {
  border: 4px solid #4caf50;
  border-radius: 12px;
  box-shadow: 0 5px 10px rgba(0,0,0,0.15);
  width: 100%;
  max-width: 400px;
}

✅ Responsive, stylish, and production-ready.


🧠 Best Practices

TipWhy It Matters
Use border-radius for rounded lookImproves design aesthetics
Add box-shadow for depthEnhances visual appeal
Combine with max-width or object-fitMakes images responsive
Always add alt textFor accessibility and SEO

🏁 Final Thoughts

Adding a border to an image with CSS is quick and powerful. With a few lines of code, you can visually separate images, draw attention, or match your website’s design style. Combine borders with rounded corners and shadows for a polished, modern look.


Spread the love
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *