ВВЕДЕНИЕ
Привет, ребята! Я все еще нахожусь на пути обучения и в настоящее время изучаю учебники по CSS на w3schools. Я должен был быть далеко впереди и, возможно, на JavaScript, но реальность такова, что промедление — это адский наркотик, и у каждого своя кривая обучения. Сегодня 7 день моего задания #100daysofcode и я изучал CSS float, комбинаторы и переполнение. Сначала я собираюсь дать общий обзор этих трех свойств, а затем объяснить их по отдельности, используя простые термины.
Свойство CSS float предназначено для указания того, как должен располагаться элемент. В основном оно используется для позиционирования и форматирования содержимого. Комбинаторы CSS объясняют взаимосвязь между селекторами. В CSS существует четыре типа комбинаторов, которые будут рассмотрены ранее. Свойство CSS overflow управляет тем, что происходит с содержимым, которое слишком велико, чтобы поместиться в области.
СВОЙСТВО FLOAT
Свойство float используется для обводки текста вокруг изображений и может иметь следующие значения;
📌Наследовать: Элементы наследуют значения float своих родителей.
📌None: Элементы не плавают (по умолчанию)
📌Right: Элементы плавают справа от своего контейнера
📌Left: Элементы плавают слева от своего контейнера
ПЛЫТЬ ВПРАВО
<!DOCTYPE html>
<html>
<head>
<style>
img {
float: right;
}
</style>
</head>
<body>
<p>In this example, the image will float to the right in the paragraph, and the text in the paragraph will wrap around the image.</p>
<p><img src="pineapple.jpg" alt="Pineapple" style="width:170px;height:170px;margin-left:15px;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit.</p>
</body>
</html>
Блок кода выше отображает фотографию, обернутую в правую часть страницы, с текстом рядом с ней. Это будет отображаться как;
FLOAT LEFT
<!DOCTYPE html>
<html>
<head>
<style>
img {
float: left;
}
</style>
</head>
<body>
<p>In this example, the image will float to the left in the paragraph, and the text in the paragraph will wrap around the image.</p>
<p><img src="pineapple.jpg" alt="Pineapple" style="width:170px;height:170px;margin-right:15px;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit.</p>
</body>
</html>
Блок кода выше отображает изображение, обернутое в левую часть страницы с текстом рядом с ним. Это отображается как;
NONE
Значение none является значением по умолчанию. В этом случае изображение будет отображаться там, где оно встречается в тексте.
<!DOCTYPE html>
<html>
<head>
<style>
img {
float: none;
}
</style>
</head>
<body>
<p>In this example, the image will be displayed just where it occurs in the text (float: none;).</p>
<p><img src="pineapple.jpg" alt="Pineapple" style="width:170px;height:170px;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit.</p>
</body>
</html>
Приведенный выше блок кода будет отображаться так;
Иногда при использовании значений left и right изображение может быть выше, чем текст на странице. Это делает внешний вид страницы эстетически неудовлетворительным. Существует так называемый «хак clearfix». Хак clearfix — это когда для устранения проблемы добавляется параметр overflow: auto. Например;
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 3px solid #4CAF50;
padding: 5px;
}
.img1 {
float: right;
}
.clearfix {
overflow: auto;
}
.img2 {
float: right;
}
</style>
</head>
<body>
<p>In this example, the image is taller than the element containing it, and it is floated, so it overflows outside of its container:</p>
<div>
<img class="img1" src="pineapple.jpg" alt="Pineapple" width="170" height="170">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum...
</div>
<p style="clear:right">Add a clearfix class with overflow: auto; to the containing element, to fix this problem:</p>
<div class="clearfix">
<img class="img2" src="pineapple.jpg" alt="Pineapple" width="170" height="170">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum...
</div>
</body>
</html>
Хак clearfix будет работать, если в контейнер div добавить класс ‘clearfix’, который содержит overflow: auto
. Приведенный выше код будет выполняться и отображаться как;
КОМБИНАТОРЫ
Комбинаторы вполне самоочевидны, потому что они объясняют взаимосвязь между селекторами. В CSS существуют различные комбинаторы. Они перечислены следующим образом;
📌 Общий селектор братьев и сестер: Обозначается символом (~). Он выбирает все элементы, которые являются братьями и сестрами указанного элемента, например;
<!DOCTYPE html>
<html>
<head>
<style>
div ~ p {
background-color: yellow;
}
</style>
</head>
<body>
<p>Paragraph 1.</p>
<div>
<p>Paragraph 2.</p>
</div>
<p>Paragraph 3.</p>
<code>Some code.</code>
<p>Paragraph 4.</p>
</body>
</html>
Блок кода выше будет отображаться как;
📌 Селектор потомков: Представляется пробелом. Он также соответствует всем элементам, которые являются потомками указанного элемента, например;
<!DOCTYPE html>
<html>
<head>
<style>
div p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section><p>Paragraph 3 in the div.</p></section>
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Блок кода выше будет отображаться как;
📌Детский селектор: Он представлен символом (>). Он выбирает все элементы, которые являются дочерними по отношению к указанному элементу.
<!DOCTYPE html>
<html>
<head>
<style>
div > p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section><p>Paragraph 3 in the div.</p></section> <!-- not Child but Descendant -->
<p>Paragraph 4 in the div.</p>
</div>
<p>Paragraph 5. Not in a div.</p>
<p>Paragraph 6. Not in a div.</p>
</body>
</html>
Блок кода выше будет отображаться как;
📌Селектор смежных сиблингов: Представляет собой символ (+). Он выбирает все элементы, которые являются смежными (ближайшими) братьями и сестрами указанного элемента, например;
<!DOCTYPE html>
<html>
<head>
<style>
div + p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
</div>
<p>Paragraph 3. Not in a div.</p>
<p>Paragraph 4. Not in a div.</p>
</body>
</html>
Блок кода выше будет отображаться как;
OVERFLOW
Свойство CSS overflow позволяет управлять тем, что происходит с содержимым, которое обычно слишком велико, чтобы поместиться на странице/экране. Свойство overflow, по сути, добавляет полосу прокрутки к содержимому или раскрывает только часть содержимого. Более подробно об этом будет рассказано ниже;
Свойство overflow имеет следующие значения;
📌auto: Добавляет полосы прокрутки только при необходимости.
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: #eee;
width: 200px;
height: 50px;
border: 1px dotted black;
overflow: auto;
}
</style>
</head>
<body>
<h2>CSS Overflow</h2>
<p>The auto value is similar to scroll, only it add scrollbars when necessary:</p>
<div>You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.</div>
</body>
</html>
Приведенный выше код будет отображаться как;
📌видимый: Вариант по умолчанию;
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: #eee;
width: 200px;
height: 50px;
border: 1px dotted black;
overflow: visible;
}
</style>
</head>
<body>
<h2>CSS Overflow</h2>
<p>By default, the overflow is visible, meaning that it is not clipped and it renders outside the element's box:</p>
<div>You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.</div>
</body>
</html>
Блок кода будет отображаться как;
📌hidden: Переполнение обрезается, и часть содержимого обрезается.
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: #eee;
width: 200px;
height: 50px;
border: 1px dotted black;
overflow: hidden;
}
</style>
</head>
<body>
<h2>CSS Overflow</h2>
<p>With the hidden value, the overflow is clipped, and the rest of the content is hidden:</p>
<p>Try to remove the overflow property to understand how it works.</p>
<div>You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.</div>
</body>
</html>
Приведенный выше код будет отображаться как;
📌scroll: Добавляется полоса прокрутки для просмотра остального содержимого страницы.
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: #eee;
width: 200px;
height: 100px;
border: 1px dotted black;
overflow: scroll;
}
</style>
</head>
<body>
<h2>CSS Overflow</h2>
<p>Setting the overflow value to scroll, the overflow is clipped and a scrollbar is added to scroll inside the box. Note that this will add a scrollbar both horizontally and vertically (even if you do not need it):</p>
<div>You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.</div>
</body>
</html>
OVERFLOW-X И OVERFLOW-Y
Эти свойства определяют, как изменять переполнение содержимого — вертикально или горизонтально.
📌overflow-x : Управляет тем, что происходит с левыми/правыми краями содержимого.
📌overflow-y: Управляет тем, что происходит с верхней/нижней границами содержимого.
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: #eee;
width: 200px;
height: 50px;
border: 1px dotted black;
overflow-x: hidden;
overflow-y: scroll;
}
</style>
</head>
<body>
<h2>CSS Overflow</h2>
<p>You can also change the overflow of content horizontally or vertically.</p>
<p>overflow-x specifies what to do with the left/right edges of the content.<br>
overflow-y specifies what to do with the top/bottom edges of the content.</p>
<div>You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.</div>
</body>
</html>
Приведенный выше код будет отображаться следующим образом;
ЗАКЛЮЧЕНИЕ
Вот и все на сегодня. Надеюсь, вам понравилось читать мою статью!