简体   繁体   English

宽度百分比值未应用于元素

[英]Width percentage value not being applied to element

I am styling an element in HTML using Sass, and when setting the width of an element using percentages, it is not applied.我正在使用 Sass 对 HTML 中的元素进行样式设置,并且在使用百分比设置元素的宽度时,它不适用。

Could this be due to me setting the parent element's width and height using "content-max"?这可能是因为我使用“content-max”设置了父元素的宽度和高度吗?

Here is a basic version of the code I am using, the idea is for the parent's size to be limited by the image size (which works), and for the text overlay to be half the width and the full height of the container element (hence me using 50 and 100 percent respectively).这是我正在使用的代码的基本版本,想法是父级的大小受图像大小的限制(有效),并且文本覆盖是容器元素的宽度和整个高度的一半(因此我分别使用 50% 和 100%)。

<div class="container">
      <img src="image.png" alt="A square image">
      <div class="text-overlay">
                
      </div>
</div>

The separately complied Sass is as follows:单独编制的Sass如下:

.container {
        
     display: block;
     position: relative;
     width: max-content;
     height: max-content;
        
     img {
          display: block;
          position: absolute;
          z-index: 0;
     }
        
     .text-overlay {
        
           display: flex;
           position: absolute;
           width: 50%;
           height: 100%;
           z-index: 1;
     }
}

Both HTML and SCSS are written in different files and correctly complied where necesary. HTML 和 SCSS 都写在不同的文件中,并在必要时正确编译。

As mentioned in the comments, you can not write Sass directly inside your HTML markup.如评论中所述,您不能直接在 HTML 标记中写入 Sass。 It has to be compiled first.它必须先编译。

In your example you are using nesting, which is not valid CSS3 code, so to fix this behavior you either have to write plain CSS like the snippet below or compile your Sass before you apply it to your HTML.在您的示例中,您正在使用嵌套,这是无效的 CSS3 代码,因此要修复此行为,您必须像下面的代码片段一样编写普通的 CSS在将其应用于 HTML 之前编译您的 Sass。


About your actual question, the positioning you are trying to archieve is working, when you hardcore the width and height to the .container element.关于您的实际问题,当您将widthheight固定到.container元素时,您试图实现的定位是有效的。


 .container { position: relative; width: 200px; height: 200px; }.container img { position: absolute; z-index: 0; }.container.text-overlay { position: absolute; z-index: 1; width: 50%; height: 100%; background-color: green; color: red; opacity: 50%; }
 <div class="container"> <img src="https://i.picsum.photos/id/793/200/200.jpg?hmac=3DeE830wjdSShKq_h_iFtV_jAxf43FO4xx-sivW0Q_Y"> <div class="text-overlay"> Overlay </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM