如何使用 css 使应用程序在不同屏幕上看起来相同?

问题描述

我目前正在尝试编写一个项目,但遇到一个问题,即应用程序的主页在不同大小的屏幕上看起来不同。是否有可能使用 CSS 以某种方式实现它在所有屏幕上看起来都相同,或者我是否需要进行响应式网页设计?我在下面添加了 2 个示例和 css 代码

enter image description here

enter image description here


body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
    background-image: url("plant.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    overflow: hidden;
}

.login-Box p {
    color: grey;
    font-size: 45px;
    left: 50%;
}

.login-Box {
    width: 280px;
    position: absolute;
    border-left-color: green;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    color: grey;
}

.login-Box h1 {
    float: inside;
    font-size: 39px;
    border-bottom: 4px solid #4caf50;
    margin-bottom: 10px;
    padding: 13px 0;
}

.h2 {
    top: 50%;
    left: 50%;
}

.textBox {
    width: 100%;
    overflow: hidden;
    font-size: 20px;
    padding: 8px 0;
    border-bottom: 1px solid #4caf50;
}

.textBox input {
    border: none;
    outline: #4caf50;
    background: none;
    font-size: 12px;
    color: white;
    width: 80px;
    float: left;
    margin: 10px;
}

.btn {
    width: 100%;
    background: none;
    border: 2px solid green;
    color: grey;
    padding: 5px;
    font-size: 20px;
    cursor: pointer;
    margin: 12px 0;
}

.btnNoAccount {
    width: 30%;
    background: none;
    border: none;
    color: grey;
    padding: 5px;
    font-size: 12px;
    cursor: pointer;
    margin: 12px 0;
    float: right;
}

.footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 2.5rem;
    left: 42%;
    color: grey;
    margin: auto;

    word-spacing: 10px;

}


解决方法

使用 JavaScript,我们可以测试窗口的宽度并相应地更改活动的 CSS 文件。这将适用于所有浏览器。您可以像任何其他元素一样拥有一个元素的 ID,所以让我们添加:

  <link rel="stylesheet" type="text/css" href="main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="narrow.css" />

然后我们可以将其用作挂钩并更改样式表的 href 值。浏览器将看到更改并取消应用旧的 CSS 并重新应用新链接的 CSS。我们将立即运行一次我们的小调整测试,然后随时调整窗口大小。

  function adjustStyle(width) {
  width = parseInt(width);
  if (width < 701) {
    $("#size-stylesheet").attr("href","css/narrow.css");
  } else if (width < 900) {
    $("#size-stylesheet").attr("href","css/medium.css");
  } else {
     $("#size-stylesheet").attr("href","css/wide.css"); 
  }
}

$(function() {
  adjustStyle($(this).width());
  $(window).resize(function() {
    adjustStyle($(this).width());
  });
});
,

您可以像下面这样使用媒体查询在 w3schools.com 中了解有关媒体查询的更多信息

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
   }
}
@media only screen and (max-width: 1100px) {
  body {
    background-color: gray;
   }
}