search
HomeWeb Front-endHTML Tutorial18 must-know HTML interview questions (with answer analysis)

This article will share with you 18 common HTML interview questions, with answer analysis, to help you consolidate your foundation. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

18 must-know HTML interview questions (with answer analysis)

HTML is one of the most widely used languages ​​for application development on the Internet. It can take us deep into the world of Web development, Improve skills. If you want to engage in a career related to WEB development (front-end development), you must be proficient in the basics of HTML. Let’s start our review in the form of a question and answer to prepare for the upcoming journey. Paving the way for new people entering this industry. [Recommended tutorial: html video tutorial]

Q1: What is HTML?

HyperText Markup Language (HyperText Markup Language, referred to as: HTML) is a standard markup language used to create web pages. HTML Makes text more interactive and dynamic, which is the cornerstone of building websites and WEB applications. HTML allows embedding of images, tables, links, and can be used to create interactive forms. It is used to structure information.

Q2: What is the difference between HTML elements and tags? The

element represents a certain structure or semantics and usually consists of a start tag, content and end tag. The

tags are , , <table>, etc. enclosed by angle brackets <code>><code> appear in pairs, such as

, . Elements Tags ## A single component of an HTML web page or document that Represents structure or semantics. For example, the titleHTML in the HTML
element represents the title of the document The root of the document is used to mark the HTML element. For example, the head tag is used to include all head elements
file Q3: What is the difference between block-level elements and inline elements?

<strong></strong>

Block-level element

: Occupies the entire space of its parent element (container), creating a "block". Usually browsers will create a new line before and after a block-level element to accommodate other block elements or inline elements. Includes:

, <div>, <code><blockquote></blockquote>, <img src="/static/imghwm/default1.png" data-src="devpoint.jpg" class="lazy" alt="18 must-know HTML interview questions (with answer analysis)" >, &lt ;section><form></form><nav></nav><h1>-<h6></h6> </h1> and <li>Inline elements

: only occupy the space contained in the border of its corresponding label, and can only accommodate text or other The element of the inline element. Includes: , <em></em>, <q></q>, <label></label>, &lt ;strong>, <a></a>, <input>

##Block-level elementsInline elementsA block-level element is drawn as a block, which can stretch to fill the entire width available to it, which is the width of its container, and Will always start on a new lineInline elements are drawn where they are defined, and only take up as much space as absolutely necessaryEvery block element is drawn on a new line Starts in a row, and the subsequent elements also start in a new row (occupy an exclusive row); the height, width, line height, and top and bottom margins of the element can be set; if the element width is not set, it occupies the space of its own parent container 100% (same width as the parent element) On the same line as other elements, not on an exclusive line; the height, width and top and bottom margins of the element cannot be set

Q4: Что такое семантический HTML?

Семантический HTML — это стиль кодирования, в котором используется разметка HTML для улучшения семантики или значения контента. В семантическом HTML тег <b> </b> используется не для жирных операторов, а для тегов <strong></strong>, а для операторов, выделенных курсивом, он используется. не . <i> </i>, вместо этого используйте <em></em>.

Q5: Перечислите часто используемые теги списков

Списки участвуют в создании страниц, и существуют специальные теги, используемые для представления данных списка в HTML Теги, а именно:

    <li> Упорядоченный список: Упорядоченный список отображает элементы в нумерованном формате, представленном <ol></ol>tags <li> Неупорядоченный список: Неупорядоченный список отображает элементы в формате маркера, который представлен тегом <ul></ul>. <li> Список определений: В списке определений элементы отображаются в форме определения, как в словаре, например <dl></dl>, <dt> # Теги ## и </dt>
    используются для определения списка описаний.

#Q6: Объясните семантику HTML-тегов<strong></strong>

HTML — это семантика разметки, а содержимое документа имеет свою собственную семантику. Общие из них следующие:

    <li>
    : используется для определения заголовка документа.
    <li> <li>
    : используется для определения единицы измерения в документе
    <li>
    : используется для определения независимых, самостоятельных статей
    <li> <li>
    : используется для определения нижнего колонтитула документа.

Q7: Что такое тикер? <strong></strong>

Эффект выделения в прошлом был классическим эффектом и был доступен практически на каждом веб-сайте.

marquee используется для прокрутки текста на веб-страницах. Он может автоматически прокручивать изображения или текст вверх, вниз, влево или вправо, пока текст, подлежащий прокрутке, помещен …… Тег < ;/marquee>.

Q8: В чем разница между div и span? Разница между

span и div заключается в том, что элемент span является встроенным и обычно используется для небольшого блока внутри строка, например внутри абзаца. А div — это уровень блока, который эквивалентен наличию символа новой строки до и после него, используемого для группировки более крупных блоков кода.

Q9: является тегом HTML?

Нет,

не является тегом HTML. Объявление называется определением типа документа (DTD). Цель объявления - сообщить браузеру тип файла. Сообщает анализатору браузера, какую спецификацию следует использовать для анализа документа. Объявление должно находиться в первой строке HTML-документа.

HTML имеет различные типы документов, такие как

HTML 4.01 Strict, HTML 4.01 Transitional, HTML 4.01 Frameset, XHTML 1.0 Strict , XHTML 1.0 Transitional, XHTML 1.0 Frameset, XHTML 1.1 и т. д. Поэтому используется для определения типа HTML-документа.

Для документов

HTML5 DTD отсутствует, поэтому нет разницы между строгим режимом и смешанным режимом. HTML5 имеет относительно свободный режим. синтаксис и реализация. На данный момент обратная совместимость реализована в максимально возможной степени.

Q10: В чем разница между HTML, XML и XHTML?

    <li>HTML: Язык гипертекстовой разметки <li>XML: Расширяемый язык разметки (язык) <li>XHTML: Расширяемый язык разметки гипертекста
##XHTML

— текущий HTML. Преемником версии является HTML в XML документ. Разница между

HTML

и XHTML заключается в следующем:

##HTML
    – это стандартный универсальный язык разметки XML. применение расширяемого языка разметки. <li> HTML Теги не чувствительны к регистру XHTML Все теги должны быть в нижнем регистре. <li> XHTML Все атрибуты должны использовать двойные кавычки. <li> HTML предназначен для отображения информации, а <li>XHTML – для информации описания . Q11: Что такое карта изображений?

Иногда необходимо добавить разные ссылки к разным областям изображения.Обычный подход заключается в использовании карт изображений в качестве горячих точек изображения. Конкретный код выглядит следующим образом:
<img src="/static/imghwm/default1.png"  data-src="devpoint.jpg"  class="lazy"   border="0" usemap="#devmap" alt="devpoint" />

<map name="devmap" id="devmap">
    <area shape="circle" coords="180,139,14" href="about.html" alt="about" />
    <area
        shape="circle"
        coords="129,161,10"
        href="contact.html"
        alt="contact"
    />
    <area shape="rect" coords="0,0,110,260" href="home.html" alt="home" />
</map>

Однако сейчас существует множество альтернатив.

Q12:超链接和锚点的区别?

HTML中的<a></a>anchor(锚)的缩写,现在把带有 href 属性的称作超链接,把没有 href 属性只有 name 属性的称作锚点连接或者命名锚点。超链接和锚点只是标签 <a></a> 的两种呈现方式。命名锚点同城用于页面定位,超链接用于页面间的跳转。

Q13:简述HTML5离线储存

现在日常使用的APP,有部分内容是使用内嵌webview的方式,浏览页面内容,这种方案的优势是WEB和APP共用一个网站,像掘金的APP就是使用这种方式。为了避免重复加载页面或者在无网络的情况下正常展现内容,可以采用离线存储,其中一种方案就是使用 manifest

在线情况下,浏览器发现HTML头部有manifest属性,它会请求manifest文件,第一次访问,那么浏览器就会根据manifest文件的内容下载相应的资源,进行离线存储。

在页面头部加入manifest属性,如下:

<html manifest="cache.manifest">

然后在cache.manifest文件中编写离线存储的资源规则,代码如下:

CACHE MANIFEST
# 2021-06-26 14:01 V0.1.2.42634241855282310056  hash 以便做版本控制
# 默认部分,显式缓存这些文件

CACHE:
#需要缓存的列表,如字体、图片、脚本、css
./assets/images/favicons/32x32.png
./assets/fonts/VideoJS.eot
./assets/fonts/VideoJS.svg
./assets/fonts/VideoJS.ttf
./assets/fonts/VideoJS.woff

# 启动页资源
./index.html

NETWORK:
#不需要缓存的
*

FALLBACK:
#访问缓存失败后,备用访问的资源,第一个是访问源,第二个是替换文件 *.html /offline.html

Q14:什么是iframe

iframe是嵌入式框架, 是html标签, 是一个内联元素, iframe 元素会创建包含另外一个文档的内联框架(即行内框架) 。通常可以使用iframe内嵌网页,跨域ajax通讯的实现,微前端,广告嵌入等。

<iframe src="home.html"></iframe>

Q15:position有哪些值?

position 属性用于指定一个元素在文档中的定位方式。toprightbottomleft 属性决定了该元素的最终位置。

    <li> static: 默认值,没有定位,指定元素使用正常的布局行为,即元素在文档常规流中当前的布局位置,此属性下 toprightbottomleftz-index 属性无效。 <li> relative 相对定位:元素先放置在未添加定位时的位置,在不改变页面布局的前提下调整元素位置(此时会在此元素未添加定位时所在位置留下空白)。position:relative table-rowtable-columntable-celltable-caption 元素无效。 <li> absolute 绝对定位:生成绝对定位的元素,元素会被移出正常文档流,并不为元素预留空间,通过指定元素相对于最近的非 static 定位祖先元素的偏移,来确定元素位置。绝对定位的元素可以设置外边距(margins),且不会与其他边距合并。 <li> fixed 固定定位:生成绝对定位的元素,元素会被移出正常文档流,并不为元素预留空间,而是通过指定元素相对于屏幕视口(viewport)的位置来指定元素位置,元素的位置在屏幕滚动时不会改变 <li> sticky 元素根据正常文档流进行定位,相对它的最近滚动祖先和最近块级祖先。

Q16:titleh1 的区别?

h1 不等于 titleh1 为大标题,一般用作文章的标题,作用如同一张报纸的大标题,使用读者在没看内容之前就大概了解本文的旨意,它是直接给用户看的。title 为页面标题,可以包含 h1 的标题,一般面对的是搜索引擎和浏览器标签。

Q17:display:nonevisibility:hidden的区别

都能把页面上的元素隐藏起来,两者的区别如下:

    <li> display:none: Скрытые объекты не занимают никакого физического пространства и не влияют на расположение других элементов <li> visible:hidden: Make объект невидим на веб-странице, но занимает физическое пространство на веб-странице. С точки зрения непрофессионала, его нельзя увидеть, но можно потрогать. <li>Будет ли выполняться повторная визуализация после изменения значения атрибута: visibility:hidden не будет отображаться; display:none будет отображаться повторно.

Q18: Перекомпоновка и перерисовка

Перекомпоновка, когда размер, структура или определенные атрибуты некоторых или всех элементов в дереве рендеринга изменяются. Процесс с помощью которого браузер повторно отображает часть или весь документ. Перерисовка, когда изменение стиля элемента на странице не влияет на его положение в потоке документа (например: color, background-color, visibility и т. д.), браузер присваивает элементу новый стиль и перерисовывает его. Эти два параметра по-разному влияют на производительность страницы, но здесь мы не будем о них говорить.

Для получения дополнительной информации о программировании посетите: Введение в программирование! !

The above is the detailed content of 18 must-know HTML interview questions (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金--天行无忌. If there is any infringement, please contact admin@php.cn delete
HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version