Intermediate CSS Tutorial (1) -- Floating and Partial Layout

1. Create a horizontal menu bar

1.1 Make a simple hyperlink horizontal menu bar

display attribute
The display attribute specifies whether/how the element is displayed.

Every HTML element has a default display value, depending on its element type. The default display value for most elements is block or inline.

block: the default method for block-level elements
inline: the default method for inline elements
hint: You can hide the navigation bar through the none attribute value, and change it to block through JS for display.

Block-level elements: occupy the entire horizontal width;
inline elements: occupy the remaining width.

The realization of the horizontal bar is to change the inline elements into a horizontal navigation bar.

Overriding the default Display value:
As mentioned earlier, every element has a default display value. However, you can override it.
Changing inline elements to block elements, and vice versa, is useful for making pages appear in a certain way while still following web standards.

A common example is generating inline <li>elements for horizontal menus:

<!DOCTYPE html>
<html>
<head>
<style>
li {
      
      
  display: inline;
}
</style>
</head>
<body>

<p>把链接列表显示为水平导航栏:</p>

<ul>
  <li><a href="/html/default.asp" target="_blank">HTML</a></li>
  <li><a href="/css/default.asp" target="_blank">CSS</a></li>
  <li><a href="/js/default.asp" target="_blank">JavaScript</a></li>
</ul>

</body>
</html>

Extension: use floathorizontal bar, see below.

<!DOCTYPE html>
<html>
<head>
<style>
ul {
      
      
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
      
      
  float: left;
}

li a {
      
      
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
      
      
  background-color: #111;
}

.active {
      
      
  background-color: red;
}
</style>
</head>
<body>

<ul>
  <li><a href="#home" class="active">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

</body>
</html>

1.2 Hide the menu bar

  • Elements can be hidden by setting displaythe attribute to none. The element will be hidden, and the page will be displayed as if the element was not there:
  • visibility:hidden; can also hide elements. However, the element will still take up the same space as before. The element will be hidden, but still affect the layout:

Combine js and css to hide and display the menu bar:

<!DOCTYPE html>
<html>
<head>
<style>
#panel, .flip {
      
      
  font-size: 16px;
  padding: 10px;
  text-align: center;
  background-color: #4CAF50;
  color: white;
  border: solid 1px #a6d8a8;
  margin: auto;
}

#panel {
      
      
  display: none;
}
</style>
</head>
<body>

<p class="flip" onclick="myFunction()">点击这里来显示面板</p>

<div id="panel">
  <p>该面板包含一个 div 元素,默认情况下该元素是隐藏的(display: none)。</p>
  <p>它使用 CSS 进行样式设置,我们使用 JavaScript 来显示它(display: block)。</p>
  <p>工作原理:请注意,带有 class="flip" 的 p 元素有 onclick 属性。当用户单击 p 元素时,将执行一个名为 myFunction() 的函数,该函数将 id="panel" 的 div 样式从 display:none(隐藏)更改为 display:block(可见)。</p>
  <p>您将在我们的 JavaScript 教程中学到有关 JavaScript 的更多知识。</p>
</div>

<script>
function myFunction() {
      
      
  document.getElementById("panel").style.display = "block";
}
</script>

</body>
</html>

Summarize:

Attributes describe
display Specifies how the element should be displayed.
visibility Specifies whether the element should be visible.

1.3 Center the menu bar

In cascading style sheets, use margin:auto.

div.ex1 {
    
    
  width: 500px;
  margin: auto;  
  border: 3px solid #73AD21;
}

2. Positioning

2.1 position attribute

positionAttributes: The position attribute specifies the type of positioning method applied to the element.

There are five different position values:
static: Statically positioned elements are not affected by the top, bottom, left, and right properties. The element box is generated normally. Block-level elements generate a rectangular box as part of the document flow, while inline elements create one or more line boxes to place within their parent element.
relative: Positions relative to its normal position. Setting the top, right, bottom, and left properties of a relatively positioned element will cause it to adjust away from its normal position.The rest of the content is not adjusted to fit any space left by the element. The element box is offset by a certain distance. The element retains its unpositioned shape, and the space it originally occupied is preserved.
absolute: The element is positioned relative to the nearest position 祖先元素(rather than relative to the viewport, as in fixed). The element box is completely removed from the document flow and positioned relative to its containing block. The containing block may be another element in the document or the initial containing block. The space the element previously occupied in the normal document flow is closed as if the element did not exist. The element is positioned to generate a block-level box, regardless of the type of box it originally generated in normal flow.
  However, if an absolutely positioned element has no ancestors, it will use the document body and move with page scrolling.

Note: A "positioned" element is any element whose position is not static. It is often used to relativedetermine the content block and absolutemodify the content inside.

fixed: elements are positioned relative to the viewport, which meansIt is always at the same position even when the page is scrolled. The top, right, bottom and left properties are used to position this element. Fixed-positioned elements leave no gaps on the page where they would normally be placed.

Note the difference fixedandsticky

sticky:ElementsPositioning based on the user's scroll position.
Sticky elements toggle between relative and fixed based on the scroll position. At first it will be relatively positioned until the given offset is encountered in the viewport - then it will be "sticked" in place (eg position:fixed).

Note: Safari requires the -webkit- prefix (see example below). You must also specify at least one of top, right, bottom, or left for sticky positioning to work.

relative positioningA hint: relative positioning is actually considered part of the normal flow positioning model, because the element's position is relative to its position in the normal flow. Offsets a little bit from the normal stream position.
absolute positioningTip: Because absolutely positioned boxes have nothing to do with document flow, they can cover other elements on the page. z-indexThe stacking order of these boxes can be controlled by setting the property.

div.sticky {
    
    
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
  background-color: green;
  border: 2px solid #4CAF50;
}

  Elements are actually positioned using the top, bottom, left and right properties. However, these properties will have no effect unless the position property is first set. Depending on the value of position, they work differently.

2.2 CSS Positioning Mechanism

CSS has three basic positioning mechanisms: normal flow, floats, and absolute positioning.

  • All boxes are positioned in normal flow unless specified otherwise. That is, the position of an element in the normal flow is determined by the position of the element in (X)HTML.
  • Block-level boxes are arranged one after another from top to bottom, and the vertical distance between boxes is calculated by the vertical margin of the box.
  • Inline boxes are laid out horizontally in a row. They can be spaced using horizontal padding, borders, and margins. However, vertical padding, borders, and margins do not affect the height of the inline box. A horizontal box formed by a row is calledLine Box, the height of a line box is always large enough to hold all the inline boxes it contains. However, setting the line height can increase the height of this box.

2.3 Element Clipping

For the element displayed by itself, clip: rect(0px,60px,200px,0px);the element is clipped, only the shape of the specified size is displayed, and the original element size will not be deformed.

2.4 Overlap or Cascade

  • When elements are positioned, they can overlap other elements. The z-index attribute specifies the stacking order of elements (which element should be placed in front or behind other elements).
  • Elements can be set positive or negativestacking order: Since the image has a z-index of -1, it is positioned behind the text.
  • Elements with a higher stacking order always precede elements with a lower stacking order.

Note: If two positioned elements overlap without specifying a z-index, the last element in the HTML code will be displayed on top.

  • img tag: an inline block element. Similar to inline-block can be wrapped by p tags. <p><img src="1.jpg"></p>For example, p is centered margin:auto, and the picture is also centered.
  • p tag: block-level element, the default width occupies one line.

Summary :

Attributes describe
bottom Sets the bottom margin edge of the positioned box.
clip Clip absolutely positioned elements.
left Sets the left margin edge of the positioned box.
position Specifies the positioning type of the element.
right Sets the right margin edge of the positioned box.
top Sets the top margin edge of the positioned box.
z-index Sets the stacking order of elements.

3. Overflow

overflowThe attribute specifies whether to clip the content or add a scroll bar when the content of the element is too large to fit in the specified area. The following values ​​can be set:

  • visible- default. Overflow is not clipped. Content is rendered outside the element's box
  • hidden- the overflow is clipped and the rest of the content will not be visible
  • scroll- overflow is clipped while adding a scrollbar to see the rest
  • auto- Similar to scroll, but only adds scrollbars when necessary

Note: The overflow property only applies to block elements with the specified height. Generally speaking, you don’t need to set a fixed height when making a website like Taobao, because you don’t know the size and height of the crawled business pictures, as well as the length of the text. The height is generally not set, and it can be flexibly scaled according to the content.

Attributes describe
overflow Specifies what happens if content overflows the element's box.
overflow-x Specifies how to handle the left/right edges of the content if the element's content area overflows.
overflow-y Specifies how to handle the top/bottom edges of the content if the element's content area overflows.

4. Float to achieve text surrounded by pictures

float Attributes specify how elements are floated. Used for positioning and formatting content, floating will cause the element to break away from the document flow, which is equivalent to floating above the document flow, and other elements will supplement it. One of the following values ​​can be set:

  • left- The element is floated to the left of its container
  • right- The element floats to the right of its container
  • none- the element will not float (will appear where it just appeared in the text),Defaults
  • inherit- The element inherits the float value from its parent

Note : All properties related to float

Attributes describe
box-sizing Defines how the width and height of elements are calculated: whether they should include padding and borders.
clear Specifies which elements can float next to the element being cleared and on which side.
float Specifies how the element should be floated.
overflow Specifies what happens if content overflows the element's box.
overflow-x Specifies how to handle the left/right edges of the content when overflowing the element's content area.
overflow-y Specifies how to handle the top/bottom edges of the content when overflowing the element's content area.

The simplest usage is that the float attribute can achieve the effect of (on a newspaper) text surrounding a picture.
pptsf4H.jpg

<!DOCTYPE html>
<html>
<head>
<style>
img {
      
      
  float: right;
}
</style>
</head>
<body>

<h1>向右浮动</h1>

<p>在本例中,图像会在段落中向右浮动,而段落中的文本会包围这幅图像。</p>

<p><img src="https://s1.ax1x.com/2023/03/20/pptssjx.jpg" alt="海贼王" style="width:220px;height:170px;margin-left:15px;">
《海贼王》是一部热血漫。 传说中‘海贼王’哥尔·D·罗杰在死前说出他留下了具有财富、名声、力量世界第一的宝藏“ONE PIECE”,许多人为了争夺“ONE PIECE”,争相出海,许多海贼开始树立霸权,而形成了“大海贼时代”。十年后,蒙其·D·路飞为了要实现与因救他而断臂的‘红发’香克斯的约定而出海,并在快乐的航海中拥有了一群值得信赖的伙伴,一起进入“伟大航道”,目标当上“海贼王”。每个伙伴都有自己的梦想,自由,友情,梦想是它的主题!</p>

</body>
</html>

Note:
1. The realization of the surround effect is based on defining an inline label in the block label, the inline label floats, and the content in the block label will surround the image, as shown in the figure above.
2. If it is defined in two line boxes (inline borders), one of the floating lines will cover the other line box.
3. CSS clearproperties specify which elements can float next to the cleared element and on which side.

5. Realize the formation of text descriptions on the pictures and the formation of card-style display

Notes on the premise:
1. To achieve the text appearing on the picture instead of above, using z-indexattributes cannot directly achieve the goal, because z-index only control the elementVertical Hierarchy[That is, whoever is displayed first on the upper layer, but cannot form a suitable block, he will occupy a whole row of line frames], cannot affect the position of the element in the horizontal direction.

2. The parent element is set to float. The main purpose is to make the picture and text be arranged in the same row or column, and the text can be displayed on the top or bottom or left or right of the picture, so as to achieve a certain layout effect. At the same time, floating allows other content to be arranged closely around pictures and text, making the layout of the page more compact and beautiful. You can use floats to display text on pictures, but you need to pay attention to some details.

3. Realize that the text appears on the picture.

  • need to be inpictureSuperimpose atext element, and set its positionattribute to absolute or relative [the parent element is set to relative, and the text element inside is preferably set to absolute, which is not easy to deform in this block], so that it can be positioned relative to the image, and then through top, left , right, bottom attributes to control the position of the text.

Proceed as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .float {
      
      
          float: left;
          position: relative; /*添加position:relative*/
        }
        .caption {
      
      
          position: absolute;
          bottom: 0;
          left: 0;
          z-index: 1;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          width: 100%;
          padding: 10px;
          box-sizing: border-box;
        }

        .container {
      
      
        float: left;
        position: relative;
      }
      .text {
      
      
        position: absolute;
        bottom: 20px;
        left: 20px;
        color: white;
        font-size: 16px;
        font-weight: bold;
      }
        </style>
        
</head>
<body>
    <div class="float">
        <img src="https://s1.ax1x.com/2023/03/20/pptssjx.jpg" alt="pptssjx.jpg" style="width:220px;height:170px;margin-left:15px;">
        <div class="caption">这里是文字说明</div>
      </div>
     
      <div class="container">
        <div class="text">这是要显示在图片上的文字</div>
        <img src="https://s1.ax1x.com/2023/03/20/pptssjx.jpg" alt="pptssjx.jpg" style="width:220px;height:170px;margin-left:15px;">
      </div>
      
</body>
</html>

Six Clear Float

6.1 Solve the floating background color problem

To prevent the line box from wrapping around the floating box, you need to apply cleara property to the box. clear The value of the attribute can be left, right, both or none,It indicates which sides of the box should not touch the floating box

Surrounding elements (background color, etc.) Surrounding floating elements:
Please add a picture description
Note:

  • A new problem arises, since there is no existing element to apply cleaning to, so we can only add an empty element and clean it, as shown in the image above. In the html parent element add<div class="clear"></div>
.clear {
    
    
  clear: both;
  }
  • There is another way, that is to float the container div. Unfortunately, the next element is affected by this floated element. To get around this, some people choose to float everything in the layout, and then clean up those floats with appropriate meaningful elements (often the site's footer). This helps reduce or eliminate unnecessary markup.
value describe
left Floated elements are not allowed on the left.
right Floating elements are not allowed on the right.
both Floated elements are not allowed on the left or right.
none Defaults. Allows floated elements to appear on both sides.
you inherit Specifies that the value of the clear attribute should be inherited from the parent element.

6.2 Solve the overflow problem caused by not setting the height (similar to the above problem)

If an element is taller than its containing element, and it's floated, it will "overflow" outside of its container. We can then fix this by adding overflow: auto; to the containing element:

.clearfix {
    
    
  overflow: auto;
}

clearfix hack to handle the layout flow. overflow: auto clearfix Works fine as long as you have control over margins and padding (otherwise you might see scrollbars) . However, the newer modern clearfix hack technique is much safer to use, the following code is used on most websites:

/* 写在父标签内。*/
.clearfix::after {
    
    
  content: "";
  clear: both;
  display: table;
}

6.3 Four ways to clear floating

1. Add height to the parent label box to prevent the height from collapsing

 	.father {
    
    
        width: 100%;
        border: 2px solid red;
        height: 300px;
      }

2. Add an empty label

      .box {
    
    
        width: 100%;
        height: 300px;
      }
      .clear {
    
    
        clear: both;

Add an empty tag of the same level under the written layout, and add the above class in the empty tag.

3. Add the overflow attribute to the parent

Add to parent tag overflow: hidden;

4. Add an after pseudo-element to the parent

The principle of this method is the same as that of the extra tag method, except that a block-level element is added behind the parent box of the floating element by using a pseudo-class.

	.clearfix::after {
    
    
        content: "";
        display: block;
        height: 0;
        clear: both;
        visibility: hidden;
      }
      .clearfix {
    
    
        /* IE6、7 专有 */
        *zoom: 1;
      }

7. Use floating to achieve layout [grid layout]

You can easily create three floaters side by side. However, when you add something that expands the width of each box (for example, padding or borders), the boxes break. The box-sizing property allows us to include padding and borders in the overall width (and height) of the box, making sure the padding stays inside the box without breaking.

Simply put: if box-sizing: border-box; is set on an element, the width and height will include padding and borders

* {
    
    
  box-sizing: border-box;
}

.box {
    
    
  float: left;
  width: 33.33%; /* 三个框(四框使用 25%,两框使用 50%,以此类推) */
  padding: 50px; /* 如果需要在图片间增加间距 */
}

Extension 1: Grid布局
Grid layout is a CSS module for web page layout, which provides a powerful way to position and align elements at the intersection of rows and columns. Grid layout allows developers to define and distribute elements on a web page in a two-dimensional grid, instead of being arranged in one direction along the horizontal or vertical axis like traditional layout methods. This allows developers to more finely control the position and size of elements on the web page, thereby achieving more complex and diverse layout effects.

Grid layout is defined bygrid container(Grid Container) andgrid item(Grid Item) to work. A grid container is an element that contains grid items, defined as a box with the display property set to grid or inline-grid. Grid items are child elements in the grid container, they are placed in cells in the grid, and can span multiple cells.

The Grid layout provides a series of properties to control the rows and columns in the grid, including , grid-template-rows, grid-template-columns, grid-template-areas, grid-row, grid-column, grid-row-start, grid-row-end, grid-column-startetc. grid-column-endBy setting these properties, developers can define the number, size, and spacing of grid rows and columns, and can place grid items in specific cells.

In general, Grid layout is a flexible and powerful layout method, which provides developers with more control and freedom, making the layout of web pages more diverse and refined.

The following are common attributes of Grid layout and their functions:

Attributes effect
grid-template-columns/grid-template-rows Defines the column/row size and number of grid containers.
grid-template-areas Defines the layout of regions within a grid container.
grid-row/grid-column Specifies the row/column position of the grid item.
grid-row-start/grid-row-end/grid-column-start/grid-column-end Specifies the row/column position where grid items start and end.
grid-column-gap/grid-row-gap Defines the spacing between grid rows/columns.
justify-items/align-items Controls the alignment of grid items on rows/columns.
justify-content/align-content Controls the alignment of the grid on rows/columns, used when the size of the grid container is larger than the grid content.
grid-auto-rows/grid-auto-columns Defines the size of rows/columns that are not explicitly sized in the grid container.
grid-auto-flow Defines the orientation and order of grid items that are automatically placed within the grid container.
grid-template Defines the column/row size and number of grid containers, and the layout of the grid areas.
grid-area Specifies the size and position of the grid item, and also gives the item a name for use in grid-template-areas.
order Defines the order of grid items within the grid container.
z-index Defines the order of grid items in the grid stacking order, with a stacking effect.

Expansion 2: Make an elastic framework, learn Flexbox 布局 by clicking here

8. Create a website using floats

<!DOCTYPE html>
<html>
<head>
<style>
* {
      
      
  box-sizing: border-box;
}

body {
      
      
  margin: 0;
}

.header {
      
      
  background-color: #2196F3;
  color: white;
  text-align: center;
  padding: 15px;
}

.footer {
      
      
  background-color: #444;
  color: white;
  padding: 15px;
}

.topmenu {
      
      
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #777;
}

.topmenu li {
      
      
  float: left;
}

.topmenu li a {
      
      
  display: inline-block;
  color: white;
  text-align: center;
  padding: 16px;
  text-decoration: none;
}

.topmenu li a:hover {
      
      
  background-color: #222;
}

.topmenu li a.active {
      
      
  color: white;
  background-color: #4CAF50;
}

.column {
      
      
  float: left;
  padding: 15px;
}

.clearfix::after {
      
      
  content: "";
  clear: both;
  display: table;
}

.sidemenu {
      
      
  width: 25%;
}

.content {
      
      
  width: 75%;
}

.sidemenu ul {
      
      
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.sidemenu li a {
      
      
  margin-bottom: 4px;
  display: block;
  padding: 8px;
  background-color: #eee;
  text-decoration: none;
  color: #666;
}

.sidemenu li a:hover {
      
      
  background-color: #555;
  color: white;
}

.sidemenu li a.active {
      
      
  background-color: #008CBA;
  color: white;
}
</style>
</head>
<body>

<ul class="topmenu">
  <li><a href="#home" class="active">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

<div class="clearfix">
  <div class="column sidemenu">
    <ul>
      <li><a href="#flight">The Flight</a></li>
      <li><a href="#city" class="active">The City</a></li>
      <li><a href="#island">The Island</a></li>
      <li><a href="#food">The Food</a></li>
      <li><a href="#people">The People</a></li>
      <li><a href="#history">The History</a></li>
      <li><a href="#oceans">The Oceans</a></li>
    </ul>
  </div>

  <div class="column content">
    <div class="header">
      <h1>The City</h1>
    </div>
    <h1>Shanghai</h1>
    <p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China. Welcome to Shanghai!
</p>
    <p>You will learn more about responsive web pages in a later chapter.</p>
  </div>
</div>

<div class="footer">
  <p>Footer Text</p>
</div>

</body>
</html>

Supplement: nesting rules for tags

Most tags can be nested freely, but there are also some special rules, for example: block-level tags such as p tags and div tags cannot be nested within p tags.
1. Block-level element nesting rules
① Special <p>、<h1> ~ <h6>、<dt>block-level elements
These elements have special rules: these tags cannot nest any block-level elements, only inline elements or inline block elements can be nested, even if we give block-level elements Setting display: inline does not work either.
If we nest block-level elements within these special elements, the browser will parse the two tags before and after the element into two pairs of tags. At this time, the style we set for the element cannot be applied to the nested element.

Guess you like

Origin blog.csdn.net/qq_54015136/article/details/129508793