如何使用 CSS 为图像添加边框?


要为图像添加边框,请使用border属性并将其设置为<img>元素。这是设置边框样式、宽度、颜色等的简写属性。边框样式可以是实线、双线、点状线等。

为图像添加边框

以下是使用 CSS 为图像添加边框的代码。我们在 img 元素中设置了边框:

img {
   border: 8px solid rgb(0, 238, 255);
   width: 400px;
   height: 400px;
}

示例

让我们来看一个为图像添加边框的示例:

<!DOCTYPE html>
<html>
<head>
   <style>
      img {
         border: 8px solid rgb(0, 238, 255);
         width: 400px;
         height: 400px;
      }
   </style>
</head>
<body>
   <h1>Border Around Image Example</h1>
   <img src="https://tutorialspoint.com/scala/images/scala-mini-logo.jpg">
</body>
</html>

为图像边框添加样式

如果要设置边框,需要为图像边框添加样式。边框有多种样式:

  • 点状线 (Dotted) - 用于指定点状边框

  • 虚线 (Dashed) - 用于指定虚线边框

  • 实线 (Solid) - 用于指定实线边框

  • 双线 (Double) - 用于指定双线边框

示例

如果不设置边框颜色,它将自动设置为黑色。让我们来看一个为图像边框添加样式的示例:

<!DOCTYPE html>
<html>
<head>
   <style>
      h1 {
         border: dotted;
      }
      p {
         border: dashed;
      }
      img {
         border: solid;
         width: 300px;
         height: 300px;
      }
   </style>
</head>
<body>
   <h1>Border Around Image Example</h1>
   <p>Set the border...</p>
   <img src="https://tutorialspoint.com/scala/images/scala-mini-logo.jpg">
</body>
</html>

为图像边框添加颜色

使用border属性,我们可以轻松设置边框颜色。但是,需要指定边框样式。让我们来看一个为图像边框添加颜色的示例:

示例

<!DOCTYPE html>
<html>
<head>
   <style>
      h1 {
         border: dotted red;
      }
      p {
         border: dashed green;
      }
      img {
         border: solid blue;
         width: 300px;
         height: 300px;
      }
   </style>
</head>
<body>
   <h1>Border Around Image Example</h1>
   <p>Set the border...</p>
   <img src="https://tutorialspoint.com/scala/images/scala-mini-logo.jpg">
</body>
</html>

为图像边框添加宽度

使用border属性,我们可以轻松设置边框宽度。但是,需要指定边框样式。让我们来看一个为图像边框添加宽度的示例:

示例

<!DOCTYPE html>
<html>
<head>
   <style>
      h1 {
         border: 3px dotted red;
      }
      p {
         border: 5px dashed green;
      }
      img {
         border: 6px solid blue;
         width: 300px;
         height: 300px;
      }
   </style>
</head>
<body>
   <h1>Border Around Image Example</h1>
   <p>Set the border...</p>
   <img src="https://tutorialspoint.com/scala/images/scala-mini-logo.jpg">
</body>
</html>

创建带边框的圆角图像

border-radius属性用于创建圆角图像。要设置边框,请使用border属性。让我们来看一个创建带边框的圆角图像的示例:

示例

<!DOCTYPE html>
<html>
<head>
   <style>
      h1 {
         border: 3px dotted red;
      }
      p {
         border: 5px dashed green;
      }
      img {
         border: 6px solid blue;
         border-radius: 30px;
         width: 300px;
         height: 300px;
      }
   </style>
</head>
<body>
   <h1>Border Around Image Example</h1>
   <p>Create rounded border...</p>
   <img src="https://tutorialspoint.com/scala/images/scala-mini-logo.jpg">
</body>
</html>

更新于:2023年11月15日

1K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.