Menu
CoddyTech

媒体查询

本课属于 Coddy HTML 学习旅程的“使用 CSS 添加样式”单元。第 72 课,共 76 课。

challenge icon

挑战

简单

在本课中,你将确保网页在不同屏幕尺寸下都能呈现良好效果。使用媒体查询,根据屏幕宽度应用不同的样式。

为宽度小于 400px的屏幕创建媒体查询。按照以下步骤操作:

  1. 使用 @media (max-width: 400px) 编写 CSS 规则,在屏幕宽度为 400px 或更小时应用样式。
  2. 选中 .menu,并将其 padding 设置为 10px,让它更紧凑。
  3. 选中 img,并将其 float 属性设置为 none,让图片在较小屏幕上移到文本上方。
  4. 将 .about 中 img 的 width 设置为 80vw,使其适应较小的屏幕。
  5. 选中 .contact 区域,并将其 height 设置为 auto ,使该区域能够根据内容扩展或收缩,确保所有元素在不同屏幕尺寸下都能正常显示并对齐。

完成这些更改后,调整浏览器窗口大小,测试页面布局如何变化。

亲手试试

<html>
    <head>
        <title>Swim with Whales in Tonga</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">  
    </head>
<body>
    <nav class="menu">
        <a href="#about">About</a>
        <a href="#experience">Experience</a>
        <a href="#contact">Contact</a>
    </nav>    
    <header class="welcome">
        <h1>Swim with Whales in Tonga</h1>
        <p>Experience the magic of swimming alongside majestic humpback whales.</p>
    </header>    
    <section class="about">
        <h2>About Tonga</h2>
        <img src="https://upload.wikimedia.org/wikipedia/commons/8/88/Hawaiian_Islands_Humpback_Whale_National_Marine_Sanctuary_breaching_2018.png">
        <p>Tonga is a stunning Polynesian archipelago in the South Pacific, famous for its crystal-clear waters and vibrant marine life. From July to October, humpback whales migrate here to breed, offering a rare chance to swim with these gentle giants. Beyond whale encounters, Tonga boasts pristine beaches, lush tropical landscapes, and a rich cultural heritage. Visitors can explore traditional villages, experience authentic Tongan hospitality, and enjoy activities like snorkeling, diving, and sailing. Whether you're seeking adventure or relaxation, Tonga provides an unforgettable escape into nature’s beauty.</p>
    </section>      
    <section class="contact">
        <h2>Plan Your Adventure</h2>
        <table>
            <tr>
                <td>Phone Number</td>
                <td>+676 123 4567</td>
            </tr>
            <tr>
                <td>Email</td>
                <td>info@tongawhales.com</td>
            </tr>
        </table>
    </section>
</body>
</html>

使用 CSS 添加样式中的所有课

自己练习: Web 在线编辑器