📌  相关文章
📜  如何使用 CSS 设置 div 宽度以适应内容?

📅  最后修改于: 2021-08-31 01:54:51             🧑  作者: Mango

解决这个问题的方法有以下三种:

  1. 默认情况下
  2. 使用内联块属性
  3. 在宽度和高度中使用 fit-content 属性

默认情况: HTML div 默认适合其中的内容。这个例子是这样的:
示例 1:



      

    
    GeeksforGeeks Example
      
    
    

  

      
    
    

        Geeks For Geeks     

       
        Cascading Style Sheets, fondly referred         to as CSS, is a simply designed language         intended to simplify the process of         making web pages presentable. CSS allows         you to apply styles to web pages. More         importantly, CSS enables you to do this         independent of the HTML that makes up         each web page.     
  

输出:

使用 inline-block 属性:使用 display: inline-block 属性根据其内容设置 div 大小。

示例 2:



  

    
      
    GeeksforGeeks Example
      
    
    

  

    
    

        Geeks For Geeks     

       
        Cascading Style Sheets, fondly referred         to as CSS, is a simply designed language         intended to simplify the process of         making web pages presentable. CSS allows         you to apply styles to web pages. More         importantly, CSS enables you to do this         independent of the HTML that makes up         each web page.     
  

输出:

在 width 和 height 中使用 fit-content 属性:在此方法中,我们将 width 和 height 属性设置为 fit-content 值。
示例 3:



      

    
    Geeks for Geeks Example
      
    
    

  

    
    

        Geeks For Geeks     

               
        Cascading Style Sheets, fondly referred         to as CSS, is a simply designed language         intended to simplify the process of          making web pages presentable. CSS allows         you to apply styles to web pages. More         importantly, CSS enables you to do this         independent of the HTML that makes up         each web page.     
  

输出: