首页 > 解决方案 > 图像未使用 % 调整为父母或祖父母的大小

问题描述

我正在从 ww3 学校网站制作一个模态。我有一个打开模态的按钮,我试图在模态中添加一个图像,但我不能根据它的任何父/祖父 div 调整图像大小。

我试过最大宽度,宽度..没有成功

它不会仅以像素为单位调整 % 的大小,据我所知,% 仅在包含 div 具有定义的高度时才有效,这会带来什么?

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 60%; /* Could be more or less, depending on screen size */
  height: 50px;
}

/* The Close Button */
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

/// END OF MODAL CSS /// END OF MODAL CSS/// END OF MODAL CSS/// END OF MODAL CSS/// END OF MODAL CSS/// END OF MODAL CSS/// END OF MODAL CSS/// END OF MODAL CSS/// END OF MODAL CSS

.image_holder{
height: 100px;
width: 100px;
}


.modal__img{
  max-height: 50%;
  max-width: 50%;
}
<body>

<button id="myBtn">Book</button>

<!-- The Modal -->
  <div id="myModal" class="modal">

  <!-- Modal content -->
   <div class="modal-content">
      <span class="close">&times;</span>
      <div class="image_holder">
            <img class="modal__img" src="https://via.placeholder.com/300.png/09f/fff"> 
        </div>
      <p>accomodationaccomodationaccomodationaccomodationaccomodationaccomodationaccomodation </p>

  </div>

</div>
<!-- Modal content -->




</body>

<script type="text/javascript" src="js/script.js"></script>

标签: htmlcss

解决方案


在这里,我为图像所做的更改以扩展其父级的整个宽度。

    .image_holder{
      height: 100%;
      width: 100%;
    }


    .modal__img{
      max-height: 100%;
      max-width: 100%;
      width: 100%;
      height: auto;
    } 

那是你想要达到的吗?

https://codepen.io/Angel-SG/pen/aPNWBZ


推荐阅读