CSS 属性选择器 : How can I style parent element but use attribute of child element?

标签 css css-selectors

<分区>

基本上,我有一个 iframe,其中包含我要选择的 src-attribute 值。我的选择器查询和应用的样式如下所示:

    .news-frame .news-modal.bt-custom-forms .modal-dialog iframe[src^="/sites/testSite/"] {
        width: 1286px !important;
    }

但是,我只想设置父 .modal-dialog 类的宽度属性的样式,而不是 iframe 的宽度。

知道如何实现吗?

谢谢!

最佳答案

不,CSS 还没有父选择器。

在 CSS 中

CSS4 选择器 :has 可以解决您的问题,但目前不支持。

MDN CSS documentation for :has

在 JavaScript 中

/* select the result div */
let resultDiv = document.getElementById("result");

/* 
 * select the first modal with these classes :
 * querySelector select only the first
 * See querySelectorAll to select all results
 */
let modal = document.querySelector(
  ".news-frame .news-modal .bt-custom-forms .modal-dialog"
);

/* check for the iframe child attribute value */
let iframeElement = document.querySelector(
  '.news-frame .news-modal .bt-custom-forms .modal-dialog iframe[src^="https://"]'
);

/* querySelector return null if no result */
if (
  null !== iframeElement 
  && null !== modal
) {
  modal.style.width = "width: 1286px !important;";
  resultDiv.innerHTML += " Good website";
} else {
  resultDiv.innerHTML += " Wrong website";
}
<div id="test">
  <div class="news-frame">
      <div class="news-modal">
          <div class="bt-custom-forms">
              <div class="modal-dialog">
                  <iframe src="https://stackoverflow.com/questions/56073820/css-attribute-selectors-how-can-i-style-parent-element-but-use-attribute-of-chi#" width="300" heigth="200">
                      <p>Your browser does not support iframes.</p>
                  </iframe>
              </div>
          </div>
      </div>
  </div>

  <div id="result"></div>
</div>

MDN JS documentation for document.querySelector

关于CSS 属性选择器 : How can I style parent element but use attribute of child element?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56073820/

上一篇:python - 我无法在 Django 模板上显示图像

下一篇:html - 将图标添加到菜单项 - 图标显示不正确,CSS 问题

相关文章:

html - 文本重叠问题

css:在图像悬停时显示灯光

jquery - css 选择器不是最后一个子元素不工作(需要纯 css 解决方案)

html - 隐藏元素,但显示 CSS 生成的内容

html - 为什么我不能选择类为 'offer' 的第一个 div?

css - 伪类和伪元素有什么区别?

css - 修改后的 CSS 下拉菜单代码

javascript - 在下拉列表中添加表行选择并删除行。仅从特定下拉列表选择中添加行一次

css - 标题后的行 (css)

在 Chrome 和 Firefox 中选择框的 Css