Without applying cascading style sheets, the form elements will be displayed in accordance with the browser used and operating system default settings. but using CSS. Allows you to create forms corresponding to the design of your site.
Decision
Form element style, like any other HTML element, can be set using CSS.
Fig. 6.1. Default form view in Firefoxi browser
Pictured by fig. 6.1 The form is decorated in accordance with the default settings used by the Firefox browser under Windows XP. Its species will change when viewing in various browsers under different platforms. Below is a typical form:
"http://www.w3.org/1999/XHTML"lang \u003d "en-us"\u003e
The appearance of this form can be changed by writing styles for elements:
form (Border: 1px dotted #aaaaaa; padding: 0 .5em;) Form Div (Margin-Bottom: 1em;) Input (Color: # 00008B; Background-Color: # Add8e6; Border: 1px Solid # 00008B;) SELECT ( width: 100px; Color: # 00008B; background-color: # add8e6; border: 1px solid # 00008B;) Textarea (Width: 200px; Height: 40px; Color: # 00008B; Background-color: # Add8e6; Border: 1px Solid # 00008B;)
Now the form looks like in Fig. 6.2.
Discussion
As you probably guessed, setpoints of styles for HTML elements fORM, INPUT, TEXTAREA and SELECT They will be applied to each of their instance located on the page with which the style table file is associated. To change the form of field fields, we can use many different properties. Using CSS you can manage almost all aspects of the field
:
Council
Forms and background color. Part of the visitors of your site can discern the colors badly, and a part may use a voice browser. Therefore, the colors should never perform important functions - for example, the instructions like "yellow fields are required to fill" should be under the complete prohibition.
Consider the properties value in more detail:
Laboratory work number 4
Cascading Style Tables (CSS)
purpose of work
Meet the concept of cascading tables styles CSS., as well as obtaining practical skills of their use.
Theoretical information.
Internet Explorer. offers you your style, called default. This style involves a white pure background, black font color, all references are underlined and blue, etc., what if you do not like all this? You already know how to change various attributes directly. Even if the same objects are the same, you already know how to apply classes. But there is another possibility. To specify the entire style of the document, the so-called hierarchical style tables are used (Cascade Style Sheets - CSS), which are a set of properties of different objects. Something they resemble classes, but if the class is created inside the document and can be applied, and maybe not, then CSS, if it is connected, the installations in it affect all objects in the document.
Introduction to CSS.
CSS is very similar to classes, only with the difference that the style is described in them for the already known object. For a visual example, inspect your room now (office, hall ...) in which you are. Surely, you will see many different items (table, chair, window, computer). Each of these object objects have characteristics, and you need to make a list of these items and their characteristics. Maybe you will have something as follows:
table:
Brown color
Material - wooden
a computer:
White color
Material - Plastics
Purpose - for work
Of course, you can go to another way, but only CSS is compiled exactly where, instead of objects, objects protrude, and their characteristics are a little different. For example, here is an excerpt of such a document:
body.
{
background-color: rgb (255,255,153);
Color: RGB (51,51,153);
}
h3.
{
Color: RGB (255,0,0);
Font-Family: Arial, Helvetica;
}
Here is asked what the style of the body and H3 element will be. Those options that are not specified by default.
Creating CSS does not require special effort and can be performed in a simple notebook, although for these purposes and exist special programsfacilitating work and clearly showing how future document will look like using this style. Look for such programs on your disk or from acquaintances.
2.2.Creating a Style Table in the Document
There are two ways to connect CSS. The first is to set it in the Style element at the beginning of the document, as a class. This is done like this (example 1):
This document
uses style tables
In this example, on the screen you will see two lines consisting of two objects: H3 and H3. Look, in which the default style of Internet Explorer has turned. But we did not make any instructions in the object itself about its style. Thus, no matter how much you have endowed objects H3 and H3, their style will always be as you specified in the stylist table.
2. 3. Style Table in separate file
If you like the style you created and you want to use it in all your documents. Or your document consists of a set HTML pages And all of them must have the same style, you do not need to enter the strings of the style table every time at the beginning of the document.
The second way to connect CSS to the Web page is creating CSS. In a separate file, and the page itself refers to this file. Then, you can write in the page only one line and still style it will be as defined in the stylist table in external file. I think it is not necessary to talk about the benefits of such a way.
So, at first you create a table, following the above rules. Then, you add to the element
To enable the string style sheet similar to the following:Link means that current page The element, REL and TYPE are connected to describe the element as a stylized table, but the HREF contains the address to which the file is with your CSS.
Dynamic change CSS.
You can dynamically change the name of the plug-in with a stylist table, accordingly, changing the style itself. Here is a function, in the JScript language, which, when calling it, if any style is already applied, removes it and connects a new one.
fUNCTION CHANGE_STYLE ()
(if (document.stylesheets.href! \u003d NULL)
document.stylesheets.href \u003d "newstyle.css";
}
If the style table is defined inside the HTML page, you can add new definitions using the AddRule function (Object, Style). Where Object is an object, and style, respectively, stylistic installations. Here is an example in which after clicking the button, a stylized table is changed (Example 2):
This document uses style sheets
This is paragraph. Click on the button to change its style
After reviewing the page with such a code, you will see how the style changes occurs by adding the installation to the style sheet.
Classes
Class is another way to install how the text should look on the page. Essentially, you define a set of styles, such as color, font thickness, its size, and so on, but do not assign it a specific tag. The class looks like this:
This example creates three classes: Regular, Superbig, Copyright. Below is shown how to apply these classes in the TEXT navigation layer.
Superbig class
Class regular
Class Copyright
You can also specifically bind the class tag. For example:
P.
{
Font-Size: 16pt;
Font-Weight: Bold;
}
P.small
(Font-Size: 9pt;
margin-left: 5em;
margin-right: 5em;
}
Below is shown how to apply the class
{ font-size:16pt;
font-weight:bold;
font-family:verdana, sans-serif;
{ font-size:9pt;
margin-left:5em;
margin-right:5em;
cool{ color: blue; font-style; italic;}
Этот документ использует стилевые таблицы
Жесткий контроль с помощью тега
Тег - это удобный универсальный инструмент для применения стиля в любом месте, где он необходим.
Этот документ использует стилевые таблицы
Этот документ
использует стилевые таблицы
Тег SPAN применяет класс coll к фразе " использует стилевые таблицы ".
Селекторы ID
Селекторы ID (сокращение от "identifier" - идентификатор) аналогичен классу, но гораздо более ограничен по своим возможностям. Каждый селектор ID может применятся в документе только один раз.
#specialOffer {font-family:gadget,
serif; font-size:40;}
селектор ID можно вызвать следующим образом:
Задание на работу
Ввести в разрабатываемый документ таблицы стилей. Изменить содержание статического HTML-документа с помощью свойств, событий и методов объектов window, событий пользовательского интерфейса, мыши, клавиатуры и т.д.
4. Контрольные вопросы
1. Что такое CSS?
2. Какие способы подключения CSS Вы знаете?
3. Каким образом происходит подключение таблицы стилей внутри документа?
4. Каким образом происходит подключение таблицы стилей из отдельного файла?
5. Как можно изменять стилевые установки, когда CSS находится внутри html - документа?
6. Для чего используются классы в CSS?
7. Преимущества использования классов?
8. Механизм действия тега .
Верстая очередной проект (или ещё только проектируя макетную сетку) многие сталкивались с дилеммой - использовать фиксированную ширину макета или «резиновую» сетку, адаптируемую под размер окна браузера.
У каждого из этих решений есть свои плюсы и минусы, хочу заострить внимание на минусах, так как обычно именно между двух зол именно в отражении минусов этих решений приходится выбирать.
Фиксированная ширина макетной сетки
Вёрстку загоняют в горизонтальный габарит 960-980 пикселей (чтобы на большинстве устройств в большинстве разрешений всё входило), что при больших горизонтальных размерах окна выглядит как-то зябко - тонкая вертикальная полоса полезного содержимого страницы и огромные бесполезные поля неиспользуемого пространства по бокам.«Резиновая» макетная сетка по ширине окна
Опять же при больших горизонтальных размерах окна есть другая проблема: строки текста становятся очень длинными, и читать их становится совсем не так комфортно, как хотелось бы.Ещё одна распространённая проблема этого решения - боковые отступы при больших горизонтальных размерах окна уже не так удачно визуально согласуются с горизонтальными размерами элементов, что также не добавляет комфорта при взгляде на свёрстанный макет.
Хочу предложить нехитрый вариант решения - ограничить минимальный горизонтальный размер фиксированным значением в пикселях, а максимальный сделать относительным в процентном соотношении к ширине окна. Это очень банально решается простыми средствами ещё 2 версии спецификации CSS.
Update: Хочу оговориться, что речь не идёт о классическом эффекте резины и об адаптации под абсолютно все разрешения, скорее лишь про некий разумный диапазон разрешений, под который проектируется макет. В примерах ниже - это классический десктопный диапазон разрешений с горизонтальным габаритом разрешения от 1024 пикселей.Ещё раз акцентирую внимание: в посте не идёт речь про решение для всех видов устройств и все диапазоны разрешений. В рамках одного макета эта задача не решаема в принципе , для её решения так или иначе потребуется несколько макетов. Мухи отдельно, котлеты отдельно.
Создаём контейнер макета:
...
Оформляем его незатейливым кодом стиля:
div.page-container { min-width: 960px; max-width: 75%; margin: 0 auto; padding: 0; }
Однако этого решения кому-то может показаться мало в силу того что при очень больших горизонтальных размерах окна опять проявляются проблемы с длиной строк. Это решается настолько же простым дополнительным приёмом: создание дополнительного внешнего контейнера внутри уже описанного и ограничение его максимальной ширины фиксированным значением (мне субъективно кажется, что лучше всего подходят значния в диапазоне 1400-1600 пикселей). Опять же используем лишь средства CSS 2.0. Такое решение вместо предложенного в первом комментарии простого добавления ширины в процентах для исходного контейнера будет работать ещё и в IE, который вплоть до 9 версии не понимает одновременного указания значений.
Дополняем HTML:
И немного меняем CSS:
div.page-container { max-width: 75%; min-width: 960px; margin: 0 auto; padding: 0; } div.page-container-inner { min-width: 960px; max-width: 1600px; margin: 0 auto; padding: 0; }
Как видите - решение предельно просто и достаточно универсально, может применяться для любых блочных элементов.
Перевод: Влад Мержевич
В CSS 2.1 фоновая картинка, применяемая к контейнеру, сохраняет свои фиксированные размеры. К счастью, в CSS3 введено свойство background-size , с помощью которого фон может быть растянут или сжат. Оно идеально подходит, если вы создаёте шаблон для адаптивного веб-дизайна.
Есть несколько способов определения размеров - взгляните на демонстрационную страницу background-size .
Абсолютное изменение размера
Могут применяться единицы измерения.
Background-size: ширина высота;
По умолчанию ширина и высота установлена как auto , что оставляет исходные размеры изображения.
Вы можете задать новый размер изображения с помощью абсолютных единиц измерения, таких как px, em, cm и др. Пропорции изменятся, если это необходимо. Например, если наша фоновая картинка имеет размеры 200×200 пикселов, то следующий код оставит эту высоту, но сделает ширину в два раза меньше:
Background-size: 100px 200px;
Если указано только одно значение, оно считается шириной. Высота устанавливается как auto и сохраняются пропорции:
Background-size: 100px; /* аналогично */ background-size: 100px auto;
Данный код масштабирует изображение с 200×200 до 100×100 пикселов.
Относительное изменение размера через проценты
Если применяются проценты, размеры основываются на элементе, а НЕ изображении:
Background-size: 50% auto;
Ширина фонового изображения, таким образом, зависит от размеров контейнера. Если у контейнера ширина 500px, то размер нашего изображения уменьшится до 250×250.
Использование процентов может быть полезно для адаптивного дизайна. Поменяйте ширину демонстрационной страницы чтобы понять, как изменяются размеры.
Масштабирование до максимального размера
Свойство background-size также понимает ключевое слово contain . Оно масштабирует изображение таким образом, чтобы оно заполняло контейнер. Другими словами, изображение будет увеличиваться или уменьшаться пропорционально, но ширина и высота не будут превышать размеры контейнера:
Background-size: contain;
Заполнение фоном
Свойство background-size также понимает ключевое слово cover . Изображение будет масштабироваться так, чтобы заполнить весь контейнер, но если различаются соотношения сторон, то картинка будет обрезана.
Background-size: cover;
Масштабирование нескольких фонов
Несколько фонов могут быть масштабированы с помощью списка значений, разделенных запятыми, идущих в том же порядке.
Background: url("sheep.png") 60% 90% no-repeat, url("sheep.png") 40% 50% no-repeat, url("sheep.png") 10% 20% no-repeat #393; background-size: 240px 210px, auto, 150px;
Работа в браузерах
Последние версии всех браузеров поддерживают background-size без префиксов.
IE8 и ниже не поддерживают это свойство. Вы можете использовать фильтр IE для эмуляции значений content и cover , но невозможно изменить размер фоновой картинки без помощи уловок, вроде добавления настоящей картинки позади других элементов. Это грязно, так что я рекомендую изящную деградацию.
» стала поводом для написания сегодняшнего поста. Суть очень схожа и речь здесь пойдет про размер шрифта.
Задача — реализовать динамическое изменение размера шрифта сайта в зависимости от разрешения экрана, т.е. размера окна браузера.
Прежде чем приступить к описанию решения, хочу обозначить два момента :
- Лично для меня полезность данной штуки весьма сомнительна , и я скорее бы рассматривал такую возможность просто в качестве ознакомления. А вот Сергей, например, эту технику давно хотел применить на практике и видит в ней смысл. Поэтому, возможно, кому-нибудь еще эта информация также пригодится.
- Решение довольно простое, работает на моем любимом jQuery, но использование этого фреймворка только ради осуществления данной задачи — не очень разумно , поскольку один лишь фреймворк «весит» под 60 Кб, а сам скрипт при этом состоит из всего лишь 10 строк. Я полагаю, что на нативном JavaScript скрипт, реализующий то же самое, будет значительно меньшего размера.
Итак, приступим.
Сначала я подробно опишу работу jQuery-скрипта, а затем объясню, как его применить к той или иной части веб-сайта.
jQuery
За точку отсчета я взял ширину в 1000 пикселей. Как правило, это минимальная ширина, под которую верстаются сайты. Заносим этот показатель в переменную:
Var width = 1000;
Теперь устанавливаем минимальный размер шрифта в пикселях, ниже которого он не будет уменьшаться:
Var bodyWidth = $("html").width();
Определяем коэффициент, на который будет умножаться базовый (минимальный) размер шрифта в зависимости от размера окна браузера. Цифру получаем путем деления ширины хтмл-документа на базовую (минимальную) ширину. Т.е., к примеру, если ширина окна браузера составляет 1600 пикселей, то получим коэффициент 1,6.
Var multiplier = bodyWidth / width;
Выполняем условие: если ширина хтмл-документа больше базовой ширины, тогда размер шрифта умножаем на коэффициент, округляя полученный результат до целого числа:
If ($("html").width() >= width) fontSize = Math.floor(fontSize * multiplier);
Теперь полученный скорректированный размер шрифта применяем к тегу
:$("body").css({fontSize: fontSize+"px"});
Все вышеописанные строки помещаем в функцию function fontSize() {} , затем запускаем эту функцию после загрузки хтмл-документа, а также после изменения размера окна браузера:
$(function() { fontSize(); }); $(window).resize(function() { fontSize(); });
Вот целиком код jQuery-скрипта, который получился у нас в итоге:
Function fontSize() { var width = 1000; // ширина, от которой идет отсчет var fontSize = 12; // минимальный размер шрифта var bodyWidth = $("html").width(); var multiplier = bodyWidth / width; if ($("html").width() >= width) fontSize = Math.floor(fontSize * multiplier); $("body").css({fontSize: fontSize+"px"}); } $(function() { fontSize(); }); $(window).resize(function() { fontSize(); });
HTML
Рассмотрим применение вышеуказанного скрипта на примере 3-колоночного макета страницы, имеющего следующую структуру HTML-кода:
CSS
Теперь осталось только использовать динамический размер шрифта для тех блоков, к которым мы хотим его применить. Давайте, для примера, сделаем так, чтобы он менялся у всей страницы, за исключение правой колонки, а у левой колонки сделаем его чуть меньше основного.
Все очень просто.
Во-первых , правой колонке мы просто-напросто устанавливаем свой фиксированный размер шрифта и высоту строки, и скрипт его не затронет:
#right { font-size: 12px; line-height: 18px; }
Во-вторых , левой колонке ставим чуть меньший размер шрифта:
#left { font-size: 0.9em; }
В-третьих , нужно либо у тега
, либо у соответствующего блока указать высоту строки в em, чтобы она тоже изменялась динамически.Если вы хотите менять размер шрифта только у конкретного блока, допустим, у #content , тогда будет логичнее в скрипте поменять body (в строке $("body").css({fontSize: fontSize+"px"});) на нужный идентификатор или класс.