html - 使用选择器将内容包装在 div 中

标签 html css css-selectors

不知道如何更好地表达它。我可以使用 CSS 选择器来注入(inject)额外的包装器吗 <div>围绕目标内容<div>

假设我的页面如下所示:

<div>
  <h3>Something</h3>
  <img src='/../../img/logo.jpg' />
</div>

我想通过css把它改成:

<div>
  <div id='newlyAddedDiv' class='something'>
    <h3>Something</h3>
    <img src='/../../img/logo.jpg' />
  </div>
</div>

这可以通过 css 选择器或伪选择器实现吗?我调查了before , after , first-child等等,但他们似乎并没有做到这一点。

编辑

问题来了。我正在使用网格(有点像照片库)并想在每个元素周围添加边距。这是 Bootstrap 4 顺便说一句。

<div id='Gallery'>
  <div class='col-3'>
    <h3>
    <img>
    <p>
  </div>
  ...
</div>

这将创建一个 4 列网格。在父 div (col-3) 上添加边距会影响网格本身(我明白为什么会这样)。我也无法向内容元素添加边距/填充(因为它们是多个)。所以我想如果我能注入(inject)一个“包装器”会很容易div围绕内容并为其添加边距。不幸的是,现在这似乎也不太可能。

最佳答案

你想改变这个:

<div id='Gallery'>
  <div class='col-3'>
    <h3>
    <img>
    <p>
  </div>
  ...
</div>

进入这个:

<div id='Gallery'>
  <div class='col-3'>
    <div class="new">
      <h3>
      <img>
      <p>
    </div>
  </div>
  ...
</div>

能够为 .new 添加边距。在这种情况下,您可以简单地将边距添加到内容中,如下所示:

.col-3 > * {
   margin:0 10px 0; /*no magin-top/bottom*/
}

.col-3 > :first-child {
   margin:10px 10px 0; /*no margin-bottom*/
}
.col-3 > :last-child {
   margin:0 10px 10px; /*no margin-top*/
}

示例代码:

img {
  width:80px;
}
.col-3 {
  outline:1px solid red;
}
.col-3 > * {
   margin:0 10px 0; /*no magin-top/bottom*/
}

.col-3 > :first-child {
   margin:10px 10px 0; /*no margin-bottom*/
}
.col-3 > :last-child {
   margin:0 10px 10px; /*no margin-top*/
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" >
<div id='Gallery' class="container">
  <div class="row">
    <div class='col-3'>
      <h3>Title</h3>
      <img src="https://picsum.photos/200/300?image=0">
    </div>
    <div class='col-3'>
      <h3>Title</h3>
      <img src="https://picsum.photos/200/300?image=0">
      <p>lorem</p>
    </div>
    <div class='col-3'>
      <h3> title</h3>
      <img src="https://picsum.photos/200/300?image=0">
      <p></p>
    </div>
    <div class='col-3'>
      <h3>title</h3>
      <img src="https://picsum.photos/200/300?image=0">
      <p></p>
    </div>
    <div class='col-3'>
      <h3>title<br>long</h3>
      <img src="https://picsum.photos/200/300?image=0">
      <p></p>
    </div>
  </div>
</div>

关于html - 使用选择器将内容包装在 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54502107/

相关文章:

javascript - 如何将外部 HTML 文件导入 TypeScript 类

html - 单击需要的大小打开一个选择框,即没有滚动条

css - 如何使用 CSS3 选择器选择每个偶数元素

css - 我应该在服务器端调整图像大小还是为 MVC 应用程序使用 css

css - 使用 CSS & SASS 选择唯一类的 child

selenium-webdriver - 如何使用 nightwatch.js 通过 Id 获取元素?

javascript - jQuery 在加载时突出显示导航项

html - iOS,在 WebView 上显示站点的特定 html 内容

html - 如何用html改变标题中的文字大小

colors - CSS - 边界半径 : background image colors don't fit