减小浏览器窗口大小时动态减小部分的宽度

时间:2021-04-24 16:01:43

标签: html css

我有一段具有这些特征的 html:

section {
background:blanchedalmond;
width: 50%;
height: 75%;
margin: 200px auto 0;
margin-top: 50px;
font-family: 'Courier New';
line-height: 150%;
font-weight: bold;
text-align: justify;
font-size: 100%;
vertical-align: middle;
}

基本上,当我减小窗口的大小时,我需要逐渐减少节外的空白空间,只有在没有空格时才开始减小“节”的大小:

enter image description here

2 个答案:

答案 0 :(得分:1)

你可以尝试过渡

section {
    background: blanchedalmond;
    width: 50%;
    height: 75%;
    margin: 200px auto 0;
    margin-top: 50px;
    font-family: 'Courier New';
    line-height: 150%;
    font-weight: bold;
    text-align: justify;
    font-size: 100%;
    vertical-align: middle;
    -moz-transition: width 1s ease-in-out, left 1.5s ease-in-out;
    -webkit-transition: width 1s ease-in-out, left 1.5s ease-in-out;
    -moz-transition: width 1s ease-in-out, left 1.5s ease-in-out;
    -o-transition: width 1s ease-in-out, left 1.5s ease-in-out;
    transition: width 1s ease-in-out, left 1.5s ease-in-out;
  }

@media (max-width: 768px) {
       section {
         width: 100%;
       }
 }

答案 1 :(得分:0)

如果我们知道屏幕的宽度发生了变化,则可以调整容器的 width。所以要弄清楚屏幕宽度发生了变化,我们需要应用媒体查询或使用 JavaScript。

媒体查询看起来像这样:

@media (max-width: 620px) {
  section {
      width: 100%;
  }
}

示例:

section {
  background: blanchedalmond;
  width: 50%;
  height: 75%;
  margin: 200px auto 0;
  margin-top: 50px;
  font-family: 'Courier New';
  line-height: 150%;
  font-weight: bold;
  text-align: justify;
  font-size: 100%;
  vertical-align: middle;
}

section {
  width: 100%;
}
 <section>
    1
  </section>

更新:

使用 JavaScript 会是这样:

const halfScreen = `50%`;

const onBodyResize = () => {
    let fooSection = document.getElementById("fooSection");
    let fooSectionClientWidth = fooSection.clientWidth;
    let windowWidth = window.innerWidth;

    if (windowWidth < 500 &&
        fooSectionClientWidth < windowWidth) {
        fooSection.style.width = `${fooSectionClientWidth + 1}px`;
        //console.log(`2 fooSection.style.width`, fooSection.clientWidth);
    }
    else if (fooSectionClientWidth >= windowWidth  ){
        fooSection.style.width = `${windowWidth}px`;
    }
    else {
        fooSection.style.width = halfScreen;
    }
}


const onLoad = () => {
    let fooSection = document.getElementById("fooSection");
    fooSection.style.width = halfScreen;
}
*, html, body {
  margin: 0;
  box-sizing: border-box;
}

section {
  background: blanchedalmond;
  height: 75%;
  margin: 200px auto 0;
  vertical-align: middle;
  margin-top: 50px;
  font-family: 'Courier New';
  line-height: 150%;
  font-weight: bold;
  text-align: justify;
  font-size: 100%;
  flex: 1 1 auto;
}
<body onload="onLoad()"  onresize="onBodyResize()">
    <section id="fooSection">
      1
    </section>
</body>

相关问题