CSS ведет себя очень странно, особенно с интервалами

Я делаю страницу с регистрационной формой для новых пользователей на моем сайте ASP.NET для создания учетных записей. Я скопировал адаптивный горизонтальный шаблон CSS-формы со следующего URL-адреса: https://www.templatemonster.com/blog/responsive-css3-form-fields-tutorial. Страница на моем сайте, использующая эту форму, называется https://maxstechandmathsite.azurewebsites.net/Регистрация. Если вы посмотрите на это, вы ясно увидите некоторые проблемы со стилем. Сначала я покажу вам важные части HTML и CSS:

HTML:

<div id = "wrapper">
<form runat = "server" onsubmit = "return false">
<h1>Personal Information</h1>
<span style = "float: right; font-size: 1.5em"><span class = "red">*</span>&nbsp;Required</span>
<div class = "col-4">
<label>
  Date of Birth (DOB) <span class = "red">*</span>
<input type = "date" required = "required" placeholder = "When is your date of birth?" id = "dob" name = "dob" tabindex = "10" />
</label>
</div>
<div class = "col-4">
  <label>
    Gender <span class = "red">*</span>
    <select id = "gender" required = "required" name = "gender" tabindex = "11">
      <option>Male</option>
      <option>Female</option>
      <option>I do not wish to identify</option>
    </select>
  </label>
</div>
<div class = "col-4 switch">
  <label>Send Text Notifications?</label>
  <center style = "position:relative; padding-bottom: 8px"><input type = "checkbox" class = "js-switch" /></center>
</div>
<div class = "col-4 switch">
  <label>Email Updates?</label>
  <center style = "position:relative; padding-bottom: 8px"><input type = "checkbox" class = "js-switch" /></center>
</div>
<div id = "BottomSection">
<br />
<h1 style = "background-color: blueviolet">Login Information</h1>
<asp:CreateUserWizard ID = "RegisterUser" runat = "server" BackColor = "#F7F7DE" BorderColor = "#CCCC99" BorderStyle = "Solid" BorderWidth = "1px" Font-Names = "Verdana" Font-Size = "10pt" OnCreatedUser = "CreateUserWizard1_CreatedUser">
</asp:CreateUserWizard>
<div style = "text-align: center; font-size: 1.5em">
    Enter password hint for future reference:
    <asp:TextBox ID = "TextBox1" runat = "server"></asp:TextBox>
    <br />
    <asp:CheckBox ID = "CheckBox1" runat = "server" />I have read and agree to the <asp:HyperLink ID = "HyperLink2" runat = "server" NavigateUrl = "~/PrivacyPolicy.html">Privacy Policy</asp:HyperLink> &nbsp;and <asp:HyperLink ID = "HyperLink1" runat = "server" NavigateUrl = "~/TermsOfService.html">Terms Of Service</asp:HyperLink>.</div>
<div class = "col-submit">
<button class = "submitbtn">Submit Form</button>
</div>
</div>
</form>
</div>

CSS:

form > div.switch > label {
   padding: 22px 20px 18px;
}

label > input {
   display: inline-block;
   position: relative;
   width: 100%;
   height: 27px;
   line-height: 27px;
   margin: 5px -5px 0;
   padding: 7px 5px 3px;
   border: none;
   outline: none;
   color: #555;
   font-family: 'Helvetica Neue', Arial, sans-serif;
   font-weight: bold;
   font-size: 14px;
   opacity: .6;
   transition: all linear .3s;
}

label > select {
   display: block;
   width: 100%;
   padding: 7px 5px 3px;
   margin: 5px -5px 0;
   color: #555;
   font-weight: 500;
   height: 35px;
   border: none;
   outline: none;
   font-family: 'Helvetica Neue', Arial, sans-serif;
   font-size: 14px;
   opacity: .6;
   transition: all linear .3s;
}

Как видите, я подправил часть кода, предоставленного из исходного кода, но это только тот код, который я исправил в лучшую сторону, так как с моей стороны он выглядит по-другому. Чтобы получить полную таблицу стилей CSS, перейдите по адресу https://maxstechandmathsite.azurewebsites.net/Style/styles.css. Вот мои проблемы:

1) Нет заголовков h1 или даже просто обычного текста HTML — например, текст со звездочкой (*) означает, что поле является обязательным, а текст рядом с флажком ASP.NET — отображаются, несмотря на отображение в файле дизайна Visual Studio.

2) Для нижнего ряда явно есть некоторые проблемы с интервалами и границами. Появляется синяя рамка, но она толще, чем синяя граница в строках выше, а также есть некоторые пробелы, а также неравномерная высота и отступы для каждого столбца в нижней строке. Я пытался настраивать и экспериментировать со многими различными значениями padding и margin, но они остаются неравномерными. Наконец, я также сделал разрыв строки (<br>), чтобы оставить место между полями формы и элементом управления ASP.NET CreateUserWizard, но он также не применяется.

Помощь приветствуется. Спасибо!

Привет, Макс. Этот вопрос слишком большой. Я предлагаю вам связать его с чем-то действительно простым, потому что / просто выяснение того, в чем ваш вопрос, - займет некоторое время. stackoverflow.com/help/как спросить - и, возможно, сделать действительно небольшой пример точных проблем в jsfiddle.net

sheriffderek 10.04.2019 04:50

@sheriffderek - Спасибо за ваш отзыв, я просто сократил свой вопрос до минимума, сохранив при этом необходимую информацию.

Max Voisard 10.04.2019 07:17

Я имел в виду действительно очень просто. В чем вопрос? Ваш CSS не «ведет себя странно» — он просто плохо написан / и делает именно то, что говорит. Это набор объявленных правил. Если вы действительно хотите изучить этот материал, я предлагаю вам разбить его намного дальше.

sheriffderek 10.04.2019 19:16

@sheriffderek - Извините, иногда для решения проблемы нужно просто много информации. Мои вопросы исходили из двух проблем, которые я перечислил в нижней части моего вопроса. Но я согласен с тем, что мой CSS не вел себя странно, а вместо этого работал так, как должен был — просто в то время это казалось странным.

Max Voisard 10.04.2019 22:22
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
1
4
119
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

1) Уберите font-size: 0 из селектора form, чтобы увидеть заголовки.

form {
  display: block;
  margin: 30px;
  overflow: hidden;
  background: #fff;
  border: 3px solid #7eaf4a;
  border-radius: 5px;
  font-size: 0;         /* <- remove this */
}

2) Обновите селектор .col-3, .col-4 с помощью vertical-align: top и min-height, чтобы они были одинаковой высоты и стиля.

.col-3, .col-4 { 
  border-bottom: 3px solid #0026ff;
  border-right: 3px solid #0026ff;
  background-color: #ebf442;
  vertical-align: top;
  min-height: 100px;
}

Я немного обновил элемент <span>Required</span> и медиа-запросы, чтобы адаптивный дизайн работал, включая упомянутые выше исправления. Фрагмент ниже:

@import url(http://fonts.googleapis.com/css?family=Laila:400,700);
@import url('https://fonts.googleapis.com/css?family=Damion|Muli:400,600');

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
  margin: 0 auto;
  text-align: center;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  outline: none;
  -webkit-font-smoothing: antialiased;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

html { overflow-y: scroll; }

body {
  font-family: Arial, Tahoma, sans-serif;
  background: #e2eef4;
  font-size: 62.5%;
  line-height: 1;
  padding-top: 40px;
}

.red { color: red }

input, textarea { 
  -webkit-font-smoothing: antialiased;
  outline: none; 
}

strong, b { font-weight: bold; }
em, i { font-style: italic; }

h1 {
  display: block;
  font-size: 3.1em;
  line-height: 1.45em;
  font-family: 'Laila', serif;
  text-align: center;
  font-weight: bold;
  text-shadow: 1px 1px 0 #fff;
  background-color: #ebf442;
}

/** form field **/
form {
  display: block;
  margin: 30px;
  overflow: hidden;
  background: #fff;
  border: 3px solid #7eaf4a;
  border-radius: 5px;
  /* font-size: 0; */
}

form > div > label {
  display: block;
  padding: 20px 20px 10px;
  vertical-align: top;
  font-size: 13px;
  font-weight: bold;
  text-transform: uppercase;
  color: #939393;
  cursor: pointer;
}

form > div.switch > label {
  padding: 22px 20px 18px;
}

.col-3, .col-4 { 
  border-bottom: 3px solid #0026ff !important;
  border-right: 3px solid #0026ff !important;
  background-color: #ebf442;
  vertical-align: top;
  min-height: 100px;
}

.col-4 {
  float: left;
}

label > input {
  display: inline-block;
  position: relative;
  width: 100%;
  height: 27px;
  line-height: 27px;
  margin: 5px -5px 0;
  padding: 7px 5px 3px;
  border: none;
  outline: none;
  color: #555;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  font-weight: bold;
  font-size: 14px;
  opacity: .6;
  transition: all linear .3s;
}

label > select {
    display: block;
    width: 100%;
    padding: 7px 5px 3px;
    margin: 5px -5px 0;
    color: #555;
    font-weight: 500;
    height: 35px;
    border: none;
    outline: none;
    font-family: 'Helvetica Neue', Arial, sans-serif;
    font-size: 14px;
    opacity: .6;
    transition: all linear .3s;
}

.col-submit {
  text-align: center;
  padding: 20px;
}

label > input:focus, label > select:focus {
  opacity: 1;
}

/** button design based on http://codepen.io/guvootes/pen/eyDAb **/
button {
  width: 100%;
  height: 35px;
  border: none;
  border-radius: 4px;
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #fff;
  font-weight: bold;
  text-shadow: 1px 1px 0 rgba(0,0,0,0.3);
  overflow: hidden;
  outline: none;
}

button.submitbtn {
  background-image: -moz-linear-gradient(#97c16b, #8ab959);
  background-image: -webkit-linear-gradient(#97c16b, #8ab959);
  background-image: linear-gradient(#97c16b, #8ab959);
  border-bottom: 1px solid #648c3a;
  cursor: pointer;
  color: #fff;
}
button.submitbtn:hover {
  background-image: -moz-linear-gradient(#8ab959, #7eaf4a);
  background-image: -webkit-linear-gradient(#8ab959, #7eaf4a);
  background-image: linear-gradient(#8ab959, #7eaf4a);
}
button.submitbtn:active {
  height: 34px;
  border-bottom: 0;
  margin: 1px 0 0 0;
  background-image: -moz-linear-gradient(#7eaf4a, #8ab959);
  background-image: -webkit-linear-gradient(#7eaf4a, #8ab959);
  background-image: linear-gradient(#7eaf4a, #8ab959);
  -moz-box-shadow: inset 0 1px 3px 1px rgba(0, 0, 0, 0.3);
  -webkit-box-shadow: inset 0 1px 3px 1px rgba(0, 0, 0, 0.3);
  box-shadow: inset 0 1px 3px 1px rgba(0, 0, 0, 0.3);
}

#BottomSection {
    background-color: #e4e4e4;
    display: block;
}

/** responsive design **/

@media(min-width: 150px) {
    form > div {
        display: inline-block;
    }

    .col-submit {
        display: block;
    }

    .col-2, .col-3, .col-4 {
        box-shadow: 1px 1px #0026ff;
        border-bottom: 1px solid #0026ff;
        border-right: 1px solid #0026ff;
    }

    .col-2 {
        width: 50%
    }

    .col-3 {
        width: 33.3333333333%
    }

    .col-4 {
        width: 25%
    }

    .col-submit button {
        width: 30%;
        margin: 0 auto;
    }
}

@media (max-width: 640px) {
    #app_body {
        padding-left: 0 !important
    }

    #main_fields div.field label, #eeoc_fields div.field label {
        float: none !important;
        width: 100% !important;
        text-align: left !important;
        display: block !important
    }

    #main_fields .field-error-msg {
        padding-left: 0 !important
    }

    #education_section .select2-container, #custom_fields .select2-container, #custom_fields div.field input[type=text], #custom_fields div.field textarea, #custom_fields div.field select, #main_fields div.field input[type=text], #main_fields div.field textarea, #eeoc_fields div.field input[type=text], #eeoc_fields div.field textarea {
        width: 100% !important;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box
    }

    #eeoc_fields div.field select, #custom_fields div.field select {
        width: 100% !important
    }

    .accessible #header {
        padding-right: 0
    }

    .accessible #resume_paste, .accessible #cover_letter_paste {
        margin-left: 0 !important
    }

    .accessible div.required-fields {
        bottom: auto;
        left: auto;
        right: 30px;
        top: 30px
    }

    .accessible #custom_fields .field label:not(:first-child) {
        margin-top: 15px;
        display: inline-block
    }

    .accessible #main_fields div.field textarea.paste, .accessible #eeoc_fields div.field textarea.paste {
        margin-left: 0
    }

    .accessible #main_fields .employment .field input[type='checkbox'] {
        margin-left: 0 !important
    }

    .accessible #main_fields .employment .field label.current {
        display: inline-block !important;
        width: auto !important
    }

    .accessible .filter-container select {
        width: 100% !important
    }

    .accessible .locate-me, .accessible .year {
        margin-top: 10px !important
    }

    .accessible #add_education, .accessible #add_employment {
        margin: 0 !important
    }

    .accessible .remove-background-field {
        position: absolute;
        margin: 0;
        top: -15px;
        right: 0
    }
  
  .col-4 {
    width: 100%;
  }
}
<div id = "wrapper">
<form runat = "server" onsubmit = "return false">
  
<h1>Personal Information</h1>
  
<span style = "font-size: 1.5em; position: absolute; z-index: 1; right: 40px;">
  <span class = "red">*</span>
  <span>&nbsp;Required</span>
</span>

  <div class = "col-4">
    <label>
      Date of Birth (DOB) <span class = "red">*</span>
    <input type = "date" required = "required" placeholder = "When is your date of birth?" id = "dob" name = "dob" tabindex = "10" />
    </label>
  </div>

  <div class = "col-4">
    <label>
      Gender <span class = "red">*</span>
      <select id = "gender" required = "required" name = "gender" tabindex = "11">
        <option>Male</option>
        <option>Female</option>
        <option>I do not wish to identify</option>
      </select>
    </label>
  </div>

  <div class = "col-4 switch">
    <label>Send Text Notifications?</label>
    <center style = "position:relative; padding-bottom: 8px"><input type = "checkbox" class = "js-switch" /></center>
  </div>

  <div class = "col-4 switch">
    <label>Email Updates?</label>
    <center style = "position:relative; padding-bottom: 8px"><input type = "checkbox" class = "js-switch" /></center>
  </div>

  
<div id = "BottomSection">
<br />
  
<h1 style = "background-color: blueviolet">Login Information</h1>
  
<asp:CreateUserWizard ID = "RegisterUser" runat = "server" BackColor = "#F7F7DE" BorderColor = "#CCCC99" BorderStyle = "Solid" BorderWidth = "1px" Font-Names = "Verdana" Font-Size = "10pt" OnCreatedUser = "CreateUserWizard1_CreatedUser">
</asp:CreateUserWizard>
<div style = "text-align: center; font-size: 1.5em">
    Enter password hint for future reference:
    <asp:TextBox ID = "TextBox1" runat = "server"></asp:TextBox>
    <br />
    <asp:CheckBox ID = "CheckBox1" runat = "server" />I have read and agree to the <asp:HyperLink ID = "HyperLink2" runat = "server" NavigateUrl = "~/PrivacyPolicy.html">Privacy Policy</asp:HyperLink> &nbsp;and <asp:HyperLink ID = "HyperLink1" runat = "server" NavigateUrl = "~/TermsOfService.html">Terms Of Service</asp:HyperLink>.</div>
<div class = "col-submit">
<button class = "submitbtn">Submit Form</button>
</div>
</div>
</form>
</div>

И если вы хотите иметь более тонкую синюю рамку, обновите значение 3px из border-right и border-bottom в селекторе .col-3, .col-4.

Andrei 10.04.2019 08:54

Андрей - большое спасибо за подробный ответ, я вижу, что вы вложили в него много времени и сил. Я должен был уделить больше внимания выяснению проблемы № 1 с font, установленным на 0 — это было легко. ОДНАКО, как только я это сделал, он каким-то образом отбросил горизонтальный интервал полей формы, так что ширина не растягивалась на всю страницу, поэтому я изменил font-size заголовков и текста с некоторым внутренним HTML. Что касается проблемы № 2, она работала идеально. Спасибо еще раз!

Max Voisard 10.04.2019 10:02

Другие вопросы по теме