如何仅在设备为 HTML/CSS 的纵向设备时显示内容?

How do I show something only if the device is portrait with HTML/CSS?

我认为这将是一项简单的任务,但我无法让它工作。

基本上,我有一个横幅,只有当用户的设备纵向时我才需要显示它。这是我的代码:

<html>

<head>
  <style>
    @media screen and (orientation: landscape) {
      #0011-rotate-device-warning {
        display: none;
      }
    }
    
    @media screen and (orientation: portrait) {
      #0011-rotate-device-warning {
        display: block;
        width: 100%;
        background-color: lightyellow;
        padding: 10px;
        border: 2px solid red;
      }
    }
  </style>
</head>

<body>


  <div id="0011-rotate-device-warning">
    <p><b>Mobile users:</b> For the best experience, please hold your device in the landscape orientation.</p>
  </div>

</body>

</html>

我希望它做的是:

实际发生的情况是,无论方向如何,显示的消息都没有任何样式。

我该如何调整它才能正常工作?

注意:这不是Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions的副本 这个问题是在 JavaScript 中寻求一种方法来做到这一点。我想纯粹使用 CSS。另外,那道题无论如何也答不上来,因为里面没有提到ID必须以数字开头的要求,原来这里才是真正的问题

id 选择器在这里不起作用,因为它以数字开头。 CSS 标识符不能以数字开头 因此,尝试从标识符的开头删除数字值,它会起作用。下面是代码:

@media (orientation: landscape) {
  #rotate-device-warning {
    display: none;
    
  }
}

@media (orientation: portrait) {
  #rotate-device-warning {
    display: block;
        width: 100%;
        background-color: lightyellow;
        padding: 10px;
        border: 2px solid red;
  }
}

html代码

  <div id="rotate-device-warning" class="warning">
    <p><b>Mobile users:</b> For the best experience, please hold your device in the landscape orientation.</p>
  </div>

您的 ID 名称应以字母开头或根据 HTML4 规范对其进行转义。

<html>

<head>
  <style>
    @media screen and (orientation: landscape) {
      #rotate-device-warning {
        display: none;
      }
    }
    
    @media screen and (orientation: portrait) {
      #rotate-device-warning {
        display: block;
        width: 100%;
        background-color: lightyellow;
        padding: 10px;
        border: 2px solid red;
      }
    }
  </style>
</head>

<body>


  <div id="rotate-device-warning">
    <p><b>Mobile users:</b> For the best experience, please hold your device in the landscape orientation.</p>
  </div>

</body>

</html>