Working with div css

How To Style the HTML element with CSS

This tutorial will introduce you to styling the HTML Content Division element—or element—using CSS. The element can be used to structure the layout of a page and break up a webpage into separate components for individual styling. In this tutorial, you will create and style elements, as well as learn how to add and style other elements inside a container. These skills will prepare you to use elements as layout tools later on in the series when you begin recreating the demonstration website.

The

element is used by adding opening and closing

tags to an HTML document. On its own, the

element typically has little visual effect on the presentation of a webpage. To specify the size, color, and other properties of a
element, you can assign it style rules using CSS.

Prerequisites

To follow this tutorial, make sure you have set up the necessary files and folders as instructed in a previous tutorial in this series How To Set Up You CSS and HTML Practice Project.

Exploring the Element in Practice

Let’s try a hands-on exercise to study how the element works. Erase everything in your styles.css file (if you added content from previous tutorials). Next, add the following CSS rule for the tag selector:

div  background-color: green; height: 100px; width: 100px; > 

Save the styles.css file. Next, return to your index.html file, erase everything that’s there (except for the first line of code: ) and add the following code snippet:

Notice that the element has opening and closing tags but does not require any content. Save the index.html file and reload it in your browser. (For instructions on loading an HTML file, please visit our tutorial step How To View An Offline HTML File In Your Browser).

Your webpage should display a green box 100 pixels wide and 100 pixels tall as specified by the CSS rule:

Webpage with green <div data-lazy-src=

Note that you have added the class as an attribute to the tag by adding the class attribute and class name to each opening tag. Save the file and reload it in your browser. You should receive something like this:

Adding and Styling Text in a Container

You can put text inside a container by inserting text in between the opening and closing tags. Try adding text inside each of the elements in your index.html file:

div class="div-1">Bluediv> div class="div-2">Reddiv> div class="div-3">Yellowdiv> 

Save the file and reload it in your browser. You should now have text displayed in each of your containers:

Webpage with elements containing text

You can add additional HTML elements to your text inside the elements. For example, try adding the HTML heading tags ( to ) to your text inside the tags in your index.html file:

div class="div-1">h2>Blueh2>div> div class="div-2">h3>Redh3>div> div class="div-3">h4>Yellowh4>div> 

Save the file and reload it in your browser. The text inside the containers should now be styled according to the default properties of the to tags:

Webpage with header text inside containers

Note that the elements have also adjusted their positions slightly. This repositioning is caused by the default margin properties of the through elements. You’ll learn more about margins in the next tutorial on the CSS Box Model, but for now it is fine to ignore them

To style text inside the containers, you can specify text property values in the rulesets for your classes. Try adding the properties and values to your rulesets in your styles.css file as highlighted in the in the following code snippet:

.div-1  background-color: blue; height: 50px; width: 50px; font-size: 10px; color: white; iu > .div-2  background-color: red; height: 100px; width: 100px; font-size: 20px; color: yellow; > .div-3  background-color: yellow; height: 200px; width: 200px; font-size:30px; color: blue; > 

Save your styles.css file and reload the index.html file in your browser. The text inside the containers should now be styled according to the CSS rules in your styles.css file:

Webpage with styled header text inside <div data-lazy-src=

: базовый блочный элемент

Элемент разделения контента HTML ( ) является универсальным контейнером для потокового контента. Он не влияет на контент или макет до тех пор, пока не будет стилизован с помощью CSS.

Интерактивный пример

Являясь «чистым» контейнером, элемент , по существу, не представляет ничего. Между тем, он используется для группировки контента, что позволяет легко его стилизовать, используя атрибуты class или id , помечать раздел документа, написанный на разных языках (используя атрибут lang ), и так далее.

Категории контента Потоковый контент, явный контент.
Допустимое содержимое Потоковый контент или (в WHATWG HTML), если родительским является элемент : один или несколько элементов , сопровождаемых одним или более элементами , в ряде случаев смешанных с элементами и .
Пропуск тегов Ни одного; Оба тега, открывающий и закрывающий, являются обязательными.
Допустимые родители Любой элемент, который разрешает потоковый контент в качестве содержимого.. Или (в WHATWG HTML): элемент .
Допустимые ARIA-роли Любые
DOM-интерфейс HTMLDivElement

Атрибуты

К этому элементу применимы глобальные атрибуты.

Примечание: Атрибут align устарел и вышел из употребления; не используйте его больше. Вместо этого, вам следует использовать свойства CSS или методы, такие как CSS Grid или CSS Flexbox для выравнивания и изменения положения элементов на странице.

Примечание

  • Элемент следует использовать только в том случае, если никакой другой семантический элемент (такой как или ) не подходит.

Примеры

Простой пример

div> p>Любой тип контента. Например, <p>, <table>. Все что угодно!p> div> 

Результат будет выглядеть так:

Стилизованный пример

Этот пример создаёт прямоугольник с тенью, применяя стили к с помощью CSS. Заметьте, что использование атрибута class на элементе даёт применение стилей «shadowbox» (в дословном переводе означает «теневая коробка») к элементу.

HTML

div class="shadowbox"> p>Вот очень интересная заметка в прекрасном прямоугольнике с тенью.p> div> 

CSS

.shadowbox  width: 15em; border: 1px solid #333; box-shadow: 8px 8px 5px #444; padding: 8px 12px; background-image: linear-gradient(180deg, #fff, #ddd 40%, #ccc); > 

Результат

Спецификации

Поддержка браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 21 июн. 2023 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

HTML | Div Tag

The div tag is known as Division tag. The div tag is used in HTML to make divisions of content in the web page like (text, images, header, footer, navigation bar, etc). Div tag has both open (

) and closing (

) tag and it is mandatory to close the tag. The Div is the most usable tag in web development because it helps us to separate out data in the web page and we can create a particular section for particular data or function in the web pages.

  • Div tag is Block level tag
  • It is a generic container tag
  • It is used to group various tags of HTML so that sections can be created and styles can be applied to them.

As we know Div tag is block-level tag, the div tag contains entire width. Hence, every div tag will start from a new line, and not the same line.

html

As we know, div tag is used for grouping HTML elements together and to apply CSS and create web layouts using it. In the below example we don’t use div tag and hence we need to apply CSS for each tag (in the example using H1 H2 and two paragraphs p tags)

html

Creating Web Layout using Div Tag The div tag is a container tag. Inside div tag, we can put more than one HTML element and can group them together and apply CSS for them. Div tag can be used for creating a layout of web pages. In the below example we had created a web layout using the div tag. We can also create web layouts using table tag but table tags are very complex to modify the layout. The div tag is very flexible in creating web layouts and easy to modify. The below example will show grouping of HTML element using div tag and create block-wise web layout.

html

Using Div tag we can cover the gap between the heading tag and the paragraph tag. This example will display a web layout with three blocks.

We can use CSS in any of the divisions ( tag) using the following methods:

1. Using class: We can use class on that particular div and apply CSS either inside a tag or linking an external CSS file.

html

html

2. Inline CSS: We can directly use CSS in div also. This method does not require class. Div in HTML coding is used as a container tag also because it is the one that can contain all other tags.

html

Difference Between div tag and span tag

The div and span tags are two commonly used tags when creating pages using HTML and performs different functionality. While div tag is a block level element and span is an inline element The div tag creates a line break and by default creates a division between the text that comes after the tag as begun and until the tag ends with

. div tag creates separate boxes or containers for all elements inside this tag like text, images, paragraphs.

Properties Div Tag Span Tag
Elements Types Block-Level Inline
Space/Width Contain Whole Width Available Takes only required Width
Examples Headings, Paragraph, form Attribute, image
Uses Web-layout container for some text
Attributes Not required,with common css, class Not required,with common css, class

The span tag does not create a line break similar to a div tag, but rather allows the user to separate things from other elements around them on a page within the same line. avoiding of line break, results only that selected text to change, keeping all the other elements around them same. Below example will display the difference between span and div tag while div tag contains whole width and span tag contain only required width and rest parts are free for another element.

Источник

Читайте также:  Profile php mode register agreed true
Оцените статью